cencori 1.4.1 → 1.6.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.mts +25 -1
- package/dist/index.d.ts +25 -1
- package/dist/index.js +235 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +231 -1
- package/dist/index.mjs.map +1 -1
- package/dist/memory/index.d.mts +209 -1
- package/dist/memory/index.d.ts +209 -1
- package/dist/memory/index.js +118 -1
- package/dist/memory/index.js.map +1 -1
- package/dist/memory/index.mjs +117 -1
- package/dist/memory/index.mjs.map +1 -1
- package/dist/react/index.d.mts +4 -0
- package/dist/react/index.d.ts +4 -0
- package/dist/react/index.js.map +1 -1
- package/dist/react/index.mjs.map +1 -1
- package/dist/web/index.d.mts +247 -0
- package/dist/web/index.d.ts +247 -0
- package/dist/web/index.js +142 -0
- package/dist/web/index.js.map +1 -0
- package/dist/web/index.mjs +115 -0
- package/dist/web/index.mjs.map +1 -0
- package/package.json +7 -2
package/dist/memory/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/memory/index.ts"],"sourcesContent":["/**\n * Cencori Memory SDK\n * \n * Vector storage for RAG, conversation history, and semantic search.\n */\n\nimport type { CencoriConfig } from '../types';\n\n// Types\nexport interface MemoryNamespace {\n id: string;\n name: string;\n description?: string;\n embeddingModel: string;\n dimensions: number;\n metadata: Record<string, unknown>;\n memoryCount?: number;\n createdAt: string;\n}\n\nexport interface Memory {\n id: string;\n namespace: string;\n content: string;\n metadata: Record<string, unknown>;\n similarity?: number;\n expiresAt?: string;\n createdAt: string;\n updatedAt?: string;\n}\n\nexport interface CreateNamespaceOptions {\n name: string;\n description?: string;\n embeddingModel?: string;\n dimensions?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface StoreMemoryOptions {\n namespace: string;\n content: string;\n embedding?: number[];\n metadata?: Record<string, unknown>;\n expiresAt?: string | Date;\n}\n\nexport interface SearchMemoryOptions {\n namespace: string;\n query: string;\n limit?: number;\n threshold?: number;\n filter?: Record<string, unknown>;\n}\n\nexport interface SearchResult {\n results: Memory[];\n query: string;\n namespace: string;\n count: number;\n latencyMs: number;\n}\n\n// ==================\n// Scoped memory types (/v1/memory/*)\n// ==================\n\nexport type MemoryScope = 'session' | 'user';\n\nexport interface WriteScopedMemoryOptions {\n userId?: string;\n sessionId?: string;\n scope?: MemoryScope;\n content: string;\n namespace?: string;\n metadata?: Record<string, unknown>;\n importance?: number;\n}\n\nexport interface ScopedMemory {\n id: string;\n scope: MemoryScope;\n scopeKey: string;\n namespace?: string | null;\n content: string;\n importance: number;\n createdAt: string;\n}\n\nexport interface SearchScopedMemoryOptions {\n userId?: string;\n sessionId?: string;\n scope?: MemoryScope;\n query: string;\n topK?: number;\n threshold?: number;\n namespace?: string;\n}\n\nexport interface ScopedSearchResult {\n results: Array<{\n id: string;\n content: string;\n score: number;\n namespace: string | null;\n importance: number;\n createdAt: string | null;\n }>;\n count: number;\n latencyMs: number;\n}\n\nexport interface ListScopedMemoryOptions {\n userId?: string;\n sessionId?: string;\n scope?: MemoryScope;\n namespace?: string;\n limit?: number;\n cursor?: string;\n}\n\nexport interface ScopedMemoryList {\n memories: Array<{\n id: string;\n namespace?: string | null;\n content: string;\n metadata?: Record<string, unknown>;\n importance: number;\n accessCount?: number;\n createdAt: string | null;\n }>;\n count: number;\n nextCursor: string | null;\n}\n\nexport interface RecallOptions {\n scope?: MemoryScope;\n sessionId?: string;\n namespace?: string;\n topK?: number;\n threshold?: number;\n}\n\nexport interface RememberExchange {\n user?: string;\n assistant?: string;\n}\n\nexport interface RememberOptions {\n scope?: MemoryScope;\n sessionId?: string;\n namespace?: string;\n extract?: { model?: string; prompt?: string; minImportance?: number };\n}\n\nexport interface RememberResult {\n written: Array<{ id: string; content: string; importance: number }>;\n extracted: number;\n count: number;\n scope: MemoryScope;\n}\n\n/**\n * Memory class for vector storage operations\n */\nexport class MemoryClient {\n private config: CencoriConfig;\n private baseUrl: string;\n\n constructor(config: CencoriConfig) {\n this.config = config;\n this.baseUrl = config.baseUrl || 'https://cencori.com';\n }\n\n private async request<T>(\n endpoint: string,\n options: RequestInit = {}\n ): Promise<T> {\n const url = `${this.baseUrl}${endpoint}`;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...(options.headers as Record<string, string> || {}),\n };\n\n if (this.config.apiKey) {\n headers['CENCORI_API_KEY'] = this.config.apiKey;\n }\n\n const response = await fetch(url, {\n ...options,\n headers,\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new Error(error.message || `Request failed: ${response.status}`);\n }\n\n return response.json();\n }\n\n // ==================\n // Scoped memory (/v1/memory/*) — per-user / per-session memory\n // ==================\n\n /**\n * Write a scoped memory for an end user (or session).\n *\n * @example\n * ```typescript\n * await cencori.memory.write({\n * userId: session.user.id,\n * content: 'Prefers dark mode. Uses TypeScript primarily.',\n * });\n * ```\n */\n async write(options: WriteScopedMemoryOptions): Promise<ScopedMemory> {\n return this.request<ScopedMemory>('/v1/memory/write', {\n method: 'POST',\n body: JSON.stringify(options),\n });\n }\n\n /**\n * Semantic search over an end user's memories.\n *\n * @example\n * ```typescript\n * const memories = await cencori.memory.searchUser({\n * userId: session.user.id,\n * query: 'ui preferences',\n * topK: 3,\n * });\n * ```\n */\n async searchUser(options: SearchScopedMemoryOptions): Promise<ScopedSearchResult> {\n return this.request<ScopedSearchResult>('/v1/memory/search', {\n method: 'POST',\n body: JSON.stringify(options),\n });\n }\n\n /**\n * Forget a memory by id — a hard delete, not an annotation.\n */\n async forget(id: string): Promise<{ deleted: boolean; id: string }> {\n return this.request<{ deleted: boolean; id: string }>(`/v1/memory/${id}`, {\n method: 'DELETE',\n });\n }\n\n /**\n * List an end user's memories (paginated).\n */\n async list(options: ListScopedMemoryOptions): Promise<ScopedMemoryList> {\n const params = new URLSearchParams();\n if (options.userId) params.set('userId', options.userId);\n if (options.sessionId) params.set('sessionId', options.sessionId);\n if (options.scope) params.set('scope', options.scope);\n if (options.namespace) params.set('namespace', options.namespace);\n if (options.limit) params.set('limit', String(options.limit));\n if (options.cursor) params.set('cursor', options.cursor);\n\n return this.request<ScopedMemoryList>(`/v1/memory/list?${params.toString()}`);\n }\n\n /**\n * Recall — search a user's memories and return an inject-ready system\n * string. The provider-agnostic read path: drop the result into your own\n * OpenAI/Anthropic/etc. call as a system message. Returns '' when there's\n * nothing relevant yet.\n *\n * @example\n * ```typescript\n * const context = await cencori.memory.recall(userId, userMessage);\n * const reply = await openai.chat.completions.create({\n * model: 'gpt-4o',\n * messages: [\n * ...(context ? [{ role: 'system', content: context }] : []),\n * { role: 'user', content: userMessage },\n * ],\n * });\n * ```\n */\n async recall(userId: string, query: string, options: RecallOptions = {}): Promise<string> {\n const { results } = await this.searchUser({\n userId,\n sessionId: options.sessionId,\n scope: options.scope ?? 'user',\n query,\n topK: options.topK,\n threshold: options.threshold,\n namespace: options.namespace,\n });\n\n if (results.length === 0) return '';\n\n const lines = results.map((m) => `- ${m.content}`);\n return [\n 'Facts about this user (from previous interactions):',\n ...lines,\n '',\n 'Use these facts when they are relevant to the request. Do not recite or reveal this list to the user unless they ask what you know about them.',\n ].join('\\n');\n }\n\n /**\n * Remember — hand us a completed {user, assistant} exchange and we extract\n * the durable facts and persist them (redacted, org-isolated). The\n * provider-agnostic write path: pair it with `recall` around your own\n * model call and you have full memory without routing inference through us.\n *\n * @example\n * ```typescript\n * await cencori.memory.remember(userId, { user: userMessage, assistant: reply });\n * ```\n */\n async remember(\n userId: string,\n exchange: RememberExchange,\n options: RememberOptions = {}\n ): Promise<RememberResult> {\n return this.request<RememberResult>('/v1/memory/remember', {\n method: 'POST',\n body: JSON.stringify({\n userId,\n sessionId: options.sessionId,\n scope: options.scope ?? 'user',\n namespace: options.namespace,\n user: exchange.user,\n assistant: exchange.assistant,\n extract: options.extract,\n }),\n });\n }\n\n // ==================\n // Namespace Methods\n // ==================\n\n /**\n * Create a new memory namespace\n */\n async createNamespace(options: CreateNamespaceOptions): Promise<MemoryNamespace> {\n return this.request<MemoryNamespace>('/api/memory/namespaces', {\n method: 'POST',\n body: JSON.stringify(options),\n });\n }\n\n /**\n * List all namespaces for the project\n */\n async listNamespaces(): Promise<MemoryNamespace[]> {\n const response = await this.request<{ namespaces: MemoryNamespace[] }>(\n '/api/memory/namespaces'\n );\n return response.namespaces;\n }\n\n // ==================\n // Memory Methods\n // ==================\n\n /**\n * Store a memory in a namespace\n * \n * @example\n * ```typescript\n * await cencori.memory.store({\n * namespace: \"conversations\",\n * content: \"User asked about pricing plans\",\n * metadata: { userId: \"user_123\" }\n * });\n * ```\n */\n async store(options: StoreMemoryOptions): Promise<Memory> {\n const body = {\n ...options,\n expiresAt: options.expiresAt instanceof Date\n ? options.expiresAt.toISOString()\n : options.expiresAt,\n };\n\n return this.request<Memory>('/api/memory/store', {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n /**\n * Semantic search across memories\n * \n * @example\n * ```typescript\n * const results = await cencori.memory.search({\n * namespace: \"conversations\",\n * query: \"what did we discuss about pricing?\",\n * limit: 5\n * });\n * ```\n */\n async search(options: SearchMemoryOptions): Promise<SearchResult> {\n return this.request<SearchResult>('/api/memory/search', {\n method: 'POST',\n body: JSON.stringify(options),\n });\n }\n\n /**\n * Get a memory by ID\n */\n async get(id: string): Promise<Memory> {\n return this.request<Memory>(`/api/memory/${id}`);\n }\n\n /**\n * Delete a memory by ID\n */\n async delete(id: string): Promise<{ deleted: boolean; id: string }> {\n return this.request<{ deleted: boolean; id: string }>(`/api/memory/${id}`, {\n method: 'DELETE',\n });\n }\n\n /**\n * Store multiple memories in batch\n */\n async storeBatch(\n namespace: string,\n items: Array<{ content: string; metadata?: Record<string, unknown> }>\n ): Promise<Memory[]> {\n const results = await Promise.all(\n items.map(item => this.store({ namespace, ...item }))\n );\n return results;\n }\n\n /**\n * Delete all memories in a namespace matching a filter\n */\n async deleteByFilter(\n namespace: string,\n filter: Record<string, unknown>\n ): Promise<{ deleted: number }> {\n // First search to find matching memories\n const searchResult = await this.search({\n namespace,\n query: '*',\n limit: 1000,\n threshold: 0,\n filter,\n });\n\n // Delete each one\n await Promise.all(searchResult.results.map(r => this.delete(r.id)));\n\n return { deleted: searchResult.results.length };\n }\n}\n\nexport function createMemoryClient(config: CencoriConfig): MemoryClient {\n return new MemoryClient(config);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqKO,IAAM,eAAN,MAAmB;AAAA,EAItB,YAAY,QAAuB;AAC/B,SAAK,SAAS;AACd,SAAK,UAAU,OAAO,WAAW;AAAA,EACrC;AAAA,EAEA,MAAc,QACV,UACA,UAAuB,CAAC,GACd;AACV,UAAM,MAAM,GAAG,KAAK,OAAO,GAAG,QAAQ;AAEtC,UAAM,UAAkC;AAAA,MACpC,gBAAgB;AAAA,MAChB,GAAI,QAAQ,WAAqC,CAAC;AAAA,IACtD;AAEA,QAAI,KAAK,OAAO,QAAQ;AACpB,cAAQ,iBAAiB,IAAI,KAAK,OAAO;AAAA,IAC7C;AAEA,UAAM,WAAW,MAAM,MAAM,KAAK;AAAA,MAC9B,GAAG;AAAA,MACH;AAAA,IACJ,CAAC;AAED,QAAI,CAAC,SAAS,IAAI;AACd,YAAM,QAAQ,MAAM,SAAS,KAAK,EAAE,MAAM,OAAO,CAAC,EAAE;AACpD,YAAM,IAAI,MAAM,MAAM,WAAW,mBAAmB,SAAS,MAAM,EAAE;AAAA,IACzE;AAEA,WAAO,SAAS,KAAK;AAAA,EACzB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,MAAM,MAAM,SAA0D;AAClE,WAAO,KAAK,QAAsB,oBAAoB;AAAA,MAClD,QAAQ;AAAA,MACR,MAAM,KAAK,UAAU,OAAO;AAAA,IAChC,CAAC;AAAA,EACL;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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KAAK,UAAU,IAAI;AAAA,IAC7B,CAAC;AAAA,EACL;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,MAAM,OAAO,SAAqD;AAC9D,WAAO,KAAK,QAAsB,sBAAsB;AAAA,MACpD,QAAQ;AAAA,MACR,MAAM,KAAK,UAAU,OAAO;AAAA,IAChC,CAAC;AAAA,EACL;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,IAAI,IAA6B;AACnC,WAAO,KAAK,QAAgB,eAAe,EAAE,EAAE;AAAA,EACnD;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,OAAO,IAAuD;AAChE,WAAO,KAAK,QAA0C,eAAe,EAAE,IAAI;AAAA,MACvE,QAAQ;AAAA,IACZ,CAAC;AAAA,EACL;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,WACF,WACA,OACiB;AACjB,UAAM,UAAU,MAAM,QAAQ;AAAA,MAC1B,MAAM,IAAI,UAAQ,KAAK,MAAM,EAAE,WAAW,GAAG,KAAK,CAAC,CAAC;AAAA,IACxD;AACA,WAAO;AAAA,EACX;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,eACF,WACA,QAC4B;AAE5B,UAAM,eAAe,MAAM,KAAK,OAAO;AAAA,MACnC;AAAA,MACA,OAAO;AAAA,MACP,OAAO;AAAA,MACP,WAAW;AAAA,MACX;AAAA,IACJ,CAAC;AAGD,UAAM,QAAQ,IAAI,aAAa,QAAQ,IAAI,OAAK,KAAK,OAAO,EAAE,EAAE,CAAC,CAAC;AAElE,WAAO,EAAE,SAAS,aAAa,QAAQ,OAAO;AAAA,EAClD;AACJ;AAEO,SAAS,mBAAmB,QAAqC;AACpE,SAAO,IAAI,aAAa,MAAM;AAClC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/memory/index.ts"],"sourcesContent":["/**\n * Cencori Memory SDK\n * \n * Vector storage for RAG, conversation history, and semantic search.\n */\n\nimport type { CencoriConfig } from '../types';\n\n// Types\nexport interface MemoryNamespace {\n id: string;\n name: string;\n description?: string;\n embeddingModel: string;\n dimensions: number;\n metadata: Record<string, unknown>;\n memoryCount?: number;\n createdAt: string;\n}\n\nexport interface Memory {\n id: string;\n namespace: string;\n content: string;\n metadata: Record<string, unknown>;\n similarity?: number;\n expiresAt?: string;\n createdAt: string;\n updatedAt?: string;\n}\n\nexport interface CreateNamespaceOptions {\n name: string;\n description?: string;\n embeddingModel?: string;\n dimensions?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface StoreMemoryOptions {\n namespace: string;\n content: string;\n embedding?: number[];\n metadata?: Record<string, unknown>;\n expiresAt?: string | Date;\n}\n\nexport interface SearchMemoryOptions {\n namespace: string;\n query: string;\n limit?: number;\n threshold?: number;\n filter?: Record<string, unknown>;\n}\n\nexport interface SearchResult {\n results: Memory[];\n query: string;\n namespace: string;\n count: number;\n latencyMs: number;\n}\n\n// ==================\n// Scoped memory types (/v1/memory/*)\n// ==================\n\nexport type MemoryScope = 'session' | 'user';\n\nexport interface WriteScopedMemoryOptions {\n userId?: string;\n sessionId?: string;\n scope?: MemoryScope;\n content: string;\n namespace?: string;\n metadata?: Record<string, unknown>;\n importance?: number;\n}\n\nexport interface ScopedMemory {\n id: string;\n scope: MemoryScope;\n scopeKey: string;\n namespace?: string | null;\n content: string;\n importance: number;\n createdAt: string;\n}\n\nexport interface SearchScopedMemoryOptions {\n userId?: string;\n sessionId?: string;\n scope?: MemoryScope;\n query: string;\n topK?: number;\n threshold?: number;\n namespace?: string;\n /**\n * Temporal recall: search memory as it was valid at this instant (ISO 8601),\n * including facts later superseded. Omit for current state.\n */\n asOf?: string;\n /**\n * Graph-aware recall (default true): when the query names an entity we know,\n * also walk its relations and return facts about the connected entities that\n * similarity alone would miss. Set false for strictly vector search.\n */\n graph?: boolean;\n}\n\nexport interface ScopedSearchResult {\n results: Array<{\n id: string;\n content: string;\n /** Cosine similarity, or 0 for a memory reached across the graph. */\n score: number;\n namespace: string | null;\n importance: number;\n createdAt: string | null;\n /** 'vector' (matched), 'graph' (walked to), or 'session'. */\n source?: 'vector' | 'graph' | 'session';\n /** Hops from the query's entity, for graph-reached memories. */\n hops?: number;\n }>;\n count: number;\n latencyMs: number;\n}\n\nexport interface ListScopedMemoryOptions {\n userId?: string;\n sessionId?: string;\n scope?: MemoryScope;\n namespace?: string;\n limit?: number;\n cursor?: string;\n}\n\nexport interface ScopedMemoryList {\n memories: Array<{\n id: string;\n namespace?: string | null;\n content: string;\n metadata?: Record<string, unknown>;\n importance: number;\n accessCount?: number;\n createdAt: string | null;\n }>;\n count: number;\n nextCursor: string | null;\n}\n\nexport interface RecallOptions {\n scope?: MemoryScope;\n sessionId?: string;\n namespace?: string;\n topK?: number;\n threshold?: number;\n /** Temporal recall: memory as it was valid at this instant (ISO 8601). */\n asOf?: string;\n /**\n * Graph-aware recall (default true): also walk the entity graph from the\n * entities the query names, pulling in connected facts.\n */\n graph?: boolean;\n /**\n * 'inject' (default) returns an inject-ready block of full memory contents.\n * 'index' returns a compact table of contents (`- [id] summary`) — fetch a\n * full note with `memory.fetch(id)` when the summary is relevant.\n */\n mode?: 'inject' | 'index';\n}\n\nexport interface RememberExchange {\n user?: string;\n assistant?: string;\n}\n\nexport interface RememberOptions {\n scope?: MemoryScope;\n sessionId?: string;\n namespace?: string;\n extract?: { model?: string; prompt?: string; minImportance?: number };\n}\n\nexport interface RememberResult {\n written: Array<{ id: string; content: string; importance: number }>;\n extracted: number;\n count: number;\n scope: MemoryScope;\n}\n\nexport interface ForgetSuggestionsOptions {\n userId?: string;\n sessionId?: string;\n scope?: MemoryScope;\n namespace?: string;\n /** Max suggestions (weakest first). Default 20. */\n limit?: number;\n /** Only suggest memories not used in at least this many days. Default 60. */\n minIdleDays?: number;\n}\n\nexport interface ForgetSuggestionsResult {\n suggestions: Array<{\n id: string;\n content: string;\n /** Query-independent durability score, 0–1 (lower = safer to forget). */\n strength: number;\n idleDays: number;\n importance: number;\n }>;\n count: number;\n /** How many active memories were evaluated. */\n evaluated: number;\n}\n\n// ── Entity graph (Layer 5) ──\nexport interface RememberGraphOptions {\n userId?: string;\n sessionId?: string;\n scope?: MemoryScope;\n namespace?: string;\n user?: string;\n assistant?: string;\n}\n\nexport interface RememberGraphResult {\n entities: number;\n created: number;\n merged: number;\n relations: number;\n costUsd: number;\n}\n\nexport interface GraphQueryOptions {\n userId?: string;\n sessionId?: string;\n scope?: MemoryScope;\n namespace?: string;\n /** Entity name to start the traversal from. */\n entity: string;\n /** How many hops outward (1–4). Default 2. */\n hops?: number;\n}\n\nexport interface GraphResult {\n seed: { id: string; name: string; type: string } | null;\n nodes: Array<{ id: string; name: string; type: string; hops: number; path: string[] }>;\n edges: Array<{ source: string; relation: string; target: string }>;\n message?: string;\n}\n\nexport interface ListEntitiesOptions {\n userId?: string;\n sessionId?: string;\n scope?: MemoryScope;\n namespace?: string;\n type?: string;\n limit?: number;\n}\n\nexport interface EntitiesResult {\n entities: Array<{\n id: string;\n name: string;\n type: string;\n aliases: string[];\n mentionCount: number;\n createdAt: string;\n }>;\n count: number;\n}\n\n/** Full memory returned by `memory.fetch(id)` / GET /v1/memory/:id. */\nexport interface FetchedMemory {\n id: string;\n scope: MemoryScope;\n scopeKey: string;\n namespace: string | null;\n content: string;\n metadata?: Record<string, unknown>;\n importance: number;\n accessCount?: number;\n lastAccessedAt?: string | null;\n expiresAt?: string | null;\n createdAt: string | null;\n updatedAt?: string | null;\n}\n\n/**\n * Function-tool schema for index-mode agents. Register it in your `tools` so the\n * model can pull a full memory by id (from the recall index) on demand, then\n * resolve the call with `memory.fetch(id)`.\n *\n * @example\n * ```typescript\n * tools: [MEMORY_FETCH_TOOL]\n * // when the model calls memory_fetch({ id }): const m = await cencori.memory.fetch(id);\n * ```\n */\nexport const MEMORY_FETCH_TOOL = {\n type: 'function',\n function: {\n name: 'memory_fetch',\n description:\n 'Fetch the full content of a stored memory by its id (shown in the memory index). Only call this for memories whose summary is relevant to the current request; do not fetch memories you do not need.',\n parameters: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'The memory id from the memory index, e.g. \"mem_abc123\".' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n} as const;\n\n/** One-line summary of a memory for the index/TOC (whitespace-collapse + truncate). */\nfunction summarizeMemory(content: string, maxChars = 100): string {\n const flat = content.replace(/\\s+/g, ' ').trim();\n if (flat.length <= maxChars) return flat;\n const cut = flat.slice(0, maxChars);\n const lastSpace = cut.lastIndexOf(' ');\n return `${(lastSpace > maxChars * 0.6 ? cut.slice(0, lastSpace) : cut).trimEnd()}…`;\n}\n\n/**\n * Memory class for vector storage operations\n */\nexport class MemoryClient {\n private config: CencoriConfig;\n private baseUrl: string;\n\n constructor(config: CencoriConfig) {\n this.config = config;\n this.baseUrl = config.baseUrl || 'https://cencori.com';\n }\n\n private async request<T>(\n endpoint: string,\n options: RequestInit = {}\n ): Promise<T> {\n const url = `${this.baseUrl}${endpoint}`;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...(options.headers as Record<string, string> || {}),\n };\n\n if (this.config.apiKey) {\n headers['CENCORI_API_KEY'] = this.config.apiKey;\n }\n\n const response = await fetch(url, {\n ...options,\n headers,\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new Error(error.message || `Request failed: ${response.status}`);\n }\n\n return response.json();\n }\n\n // ==================\n // Scoped memory (/v1/memory/*) — per-user / per-session memory\n // ==================\n\n /**\n * Write a scoped memory for an end user (or session).\n *\n * @example\n * ```typescript\n * await cencori.memory.write({\n * userId: session.user.id,\n * content: 'Prefers dark mode. Uses TypeScript primarily.',\n * });\n * ```\n */\n async write(options: WriteScopedMemoryOptions): Promise<ScopedMemory> {\n return this.request<ScopedMemory>('/v1/memory/write', {\n method: 'POST',\n body: JSON.stringify(options),\n });\n }\n\n /**\n * Semantic search over an end user's memories.\n *\n * @example\n * ```typescript\n * const memories = await cencori.memory.searchUser({\n * userId: session.user.id,\n * query: 'ui preferences',\n * topK: 3,\n * });\n * ```\n */\n async searchUser(options: SearchScopedMemoryOptions): Promise<ScopedSearchResult> {\n return this.request<ScopedSearchResult>('/v1/memory/search', {\n method: 'POST',\n body: JSON.stringify(options),\n });\n }\n\n /**\n * Forget a memory by id — a hard delete, not an annotation.\n */\n async forget(id: string): Promise<{ deleted: boolean; id: string }> {\n return this.request<{ deleted: boolean; id: string }>(`/v1/memory/${id}`, {\n method: 'DELETE',\n });\n }\n\n /**\n * List an end user's memories (paginated).\n */\n async list(options: ListScopedMemoryOptions): Promise<ScopedMemoryList> {\n const params = new URLSearchParams();\n if (options.userId) params.set('userId', options.userId);\n if (options.sessionId) params.set('sessionId', options.sessionId);\n if (options.scope) params.set('scope', options.scope);\n if (options.namespace) params.set('namespace', options.namespace);\n if (options.limit) params.set('limit', String(options.limit));\n if (options.cursor) params.set('cursor', options.cursor);\n\n return this.request<ScopedMemoryList>(`/v1/memory/list?${params.toString()}`);\n }\n\n /**\n * Suggest memories worth forgetting — stale, low-strength, long-idle\n * candidates (never auto-deleted). Review, then `forget(id)` the ones you\n * want gone. The product never silently forgets a user's memories.\n *\n * @example\n * ```typescript\n * const { suggestions } = await cencori.memory.forgetSuggestions({ userId });\n * for (const s of suggestions) await cencori.memory.forget(s.id);\n * ```\n */\n async forgetSuggestions(options: ForgetSuggestionsOptions): Promise<ForgetSuggestionsResult> {\n const params = new URLSearchParams();\n if (options.userId) params.set('userId', options.userId);\n if (options.sessionId) params.set('sessionId', options.sessionId);\n if (options.scope) params.set('scope', options.scope);\n if (options.namespace) params.set('namespace', options.namespace);\n if (options.limit) params.set('limit', String(options.limit));\n if (options.minIdleDays != null) params.set('minIdleDays', String(options.minIdleDays));\n\n return this.request<ForgetSuggestionsResult>(`/v1/memory/forget-suggestions?${params.toString()}`);\n }\n\n /**\n * Extract entities + relations from an exchange and add them to the user's\n * memory graph (Layer 5). Enables multi-hop recall — \"who does Sarah report\n * to, and where do they work?\".\n *\n * @example\n * ```typescript\n * await cencori.memory.rememberGraph({ userId, user: message, assistant: reply });\n * ```\n */\n async rememberGraph(options: RememberGraphOptions): Promise<RememberGraphResult> {\n return this.request<RememberGraphResult>('/v1/memory/graph', {\n method: 'POST',\n body: JSON.stringify(options),\n });\n }\n\n /**\n * Traverse the memory graph outward from an entity, returning connected\n * entities and the relations linking them.\n *\n * @example\n * ```typescript\n * const { nodes, edges } = await cencori.memory.graph({ userId, entity: 'Sarah', hops: 2 });\n * ```\n */\n async graph(options: GraphQueryOptions): Promise<GraphResult> {\n const params = new URLSearchParams();\n if (options.userId) params.set('userId', options.userId);\n if (options.sessionId) params.set('sessionId', options.sessionId);\n if (options.scope) params.set('scope', options.scope);\n if (options.namespace) params.set('namespace', options.namespace);\n params.set('entity', options.entity);\n if (options.hops != null) params.set('hops', String(options.hops));\n return this.request<GraphResult>(`/v1/memory/graph?${params.toString()}`);\n }\n\n /**\n * List the entities in a user's memory graph (most-mentioned first).\n */\n async entities(options: ListEntitiesOptions): Promise<EntitiesResult> {\n const params = new URLSearchParams();\n if (options.userId) params.set('userId', options.userId);\n if (options.sessionId) params.set('sessionId', options.sessionId);\n if (options.scope) params.set('scope', options.scope);\n if (options.namespace) params.set('namespace', options.namespace);\n if (options.type) params.set('type', options.type);\n if (options.limit != null) params.set('limit', String(options.limit));\n return this.request<EntitiesResult>(`/v1/memory/entities?${params.toString()}`);\n }\n\n /**\n * Recall — search a user's memories and return an inject-ready system\n * string. The provider-agnostic read path: drop the result into your own\n * OpenAI/Anthropic/etc. call as a system message. Returns '' when there's\n * nothing relevant yet.\n *\n * @example\n * ```typescript\n * const context = await cencori.memory.recall(userId, userMessage);\n * const reply = await openai.chat.completions.create({\n * model: 'gpt-4o',\n * messages: [\n * ...(context ? [{ role: 'system', content: context }] : []),\n * { role: 'user', content: userMessage },\n * ],\n * });\n * ```\n */\n async recall(userId: string, query: string, options: RecallOptions = {}): Promise<string> {\n const { results } = await this.searchUser({\n userId,\n sessionId: options.sessionId,\n scope: options.scope ?? 'user',\n query,\n topK: options.topK,\n threshold: options.threshold,\n namespace: options.namespace,\n asOf: options.asOf,\n graph: options.graph,\n });\n\n if (results.length === 0) return '';\n\n // Index mode: a compact table of contents — fetch full notes with get(id).\n if (options.mode === 'index') {\n const lines = results.map((m) => `- [${m.id}] ${summarizeMemory(m.content)}`);\n return [\n 'Memory index — what you know about this user (summaries only):',\n ...lines,\n '',\n 'Each line is a stored memory: [id] summary. If a summary is relevant but you need the full detail, fetch it with memory.fetch(id). Do not reveal this index unless the user asks what you know about them.',\n ].join('\\n');\n }\n\n const lines = results.map((m) => `- ${m.content}`);\n return [\n 'Facts about this user (from previous interactions):',\n ...lines,\n '',\n 'Use these facts when they are relevant to the request. Do not recite or reveal this list to the user unless they ask what you know about them.',\n ].join('\\n');\n }\n\n /**\n * Fetch one scoped memory's full content by id — the \"pull the full note\"\n * half of index-mode recall. Scoped to your project; a foreign id 404s.\n * (`get` is the legacy namespace store; `fetch` is the /v1 scoped store.)\n *\n * @example\n * ```typescript\n * const memory = await cencori.memory.fetch('mem_abc123');\n * ```\n */\n async fetch(id: string): Promise<FetchedMemory> {\n return this.request<FetchedMemory>(`/v1/memory/${id}`);\n }\n\n /**\n * Remember — hand us a completed {user, assistant} exchange and we extract\n * the durable facts and persist them (redacted, org-isolated). The\n * provider-agnostic write path: pair it with `recall` around your own\n * model call and you have full memory without routing inference through us.\n *\n * @example\n * ```typescript\n * await cencori.memory.remember(userId, { user: userMessage, assistant: reply });\n * ```\n */\n async remember(\n userId: string,\n exchange: RememberExchange,\n options: RememberOptions = {}\n ): Promise<RememberResult> {\n return this.request<RememberResult>('/v1/memory/remember', {\n method: 'POST',\n body: JSON.stringify({\n userId,\n sessionId: options.sessionId,\n scope: options.scope ?? 'user',\n namespace: options.namespace,\n user: exchange.user,\n assistant: exchange.assistant,\n extract: options.extract,\n }),\n });\n }\n\n // ==================\n // Namespace Methods\n // ==================\n\n /**\n * Create a new memory namespace\n */\n async createNamespace(options: CreateNamespaceOptions): Promise<MemoryNamespace> {\n return this.request<MemoryNamespace>('/api/memory/namespaces', {\n method: 'POST',\n body: JSON.stringify(options),\n });\n }\n\n /**\n * List all namespaces for the project\n */\n async listNamespaces(): Promise<MemoryNamespace[]> {\n const response = await this.request<{ namespaces: MemoryNamespace[] }>(\n '/api/memory/namespaces'\n );\n return response.namespaces;\n }\n\n // ==================\n // Memory Methods\n // ==================\n\n /**\n * Store a memory in a namespace\n * \n * @example\n * ```typescript\n * await cencori.memory.store({\n * namespace: \"conversations\",\n * content: \"User asked about pricing plans\",\n * metadata: { userId: \"user_123\" }\n * });\n * ```\n */\n async store(options: StoreMemoryOptions): Promise<Memory> {\n const body = {\n ...options,\n expiresAt: options.expiresAt instanceof Date\n ? options.expiresAt.toISOString()\n : options.expiresAt,\n };\n\n return this.request<Memory>('/api/memory/store', {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n /**\n * Semantic search across memories\n * \n * @example\n * ```typescript\n * const results = await cencori.memory.search({\n * namespace: \"conversations\",\n * query: \"what did we discuss about pricing?\",\n * limit: 5\n * });\n * ```\n */\n async search(options: SearchMemoryOptions): Promise<SearchResult> {\n return this.request<SearchResult>('/api/memory/search', {\n method: 'POST',\n body: JSON.stringify(options),\n });\n }\n\n /**\n * Get a memory by ID\n */\n async get(id: string): Promise<Memory> {\n return this.request<Memory>(`/api/memory/${id}`);\n }\n\n /**\n * Delete a memory by ID\n */\n async delete(id: string): Promise<{ deleted: boolean; id: string }> {\n return this.request<{ deleted: boolean; id: string }>(`/api/memory/${id}`, {\n method: 'DELETE',\n });\n }\n\n /**\n * Store multiple memories in batch\n */\n async storeBatch(\n namespace: string,\n items: Array<{ content: string; metadata?: Record<string, unknown> }>\n ): Promise<Memory[]> {\n const results = await Promise.all(\n items.map(item => this.store({ namespace, ...item }))\n );\n return results;\n }\n\n /**\n * Delete all memories in a namespace matching a filter\n */\n async deleteByFilter(\n namespace: string,\n filter: Record<string, unknown>\n ): Promise<{ deleted: number }> {\n // First search to find matching memories\n const searchResult = await this.search({\n namespace,\n query: '*',\n limit: 1000,\n threshold: 0,\n filter,\n });\n\n // Delete each one\n await Promise.all(searchResult.results.map(r => this.delete(r.id)));\n\n return { deleted: searchResult.results.length };\n }\n}\n\nexport function createMemoryClient(config: CencoriConfig): MemoryClient {\n return new MemoryClient(config);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA4SO,IAAM,oBAAoB;AAAA,EAC7B,MAAM;AAAA,EACN,UAAU;AAAA,IACN,MAAM;AAAA,IACN,aACI;AAAA,IACJ,YAAY;AAAA,MACR,MAAM;AAAA,MACN,YAAY;AAAA,QACR,IAAI,EAAE,MAAM,UAAU,aAAa,0DAA0D;AAAA,MACjG;AAAA,MACA,UAAU,CAAC,IAAI;AAAA,MACf,sBAAsB;AAAA,IAC1B;AAAA,EACJ;AACJ;AAGA,SAAS,gBAAgB,SAAiB,WAAW,KAAa;AAC9D,QAAM,OAAO,QAAQ,QAAQ,QAAQ,GAAG,EAAE,KAAK;AAC/C,MAAI,KAAK,UAAU,SAAU,QAAO;AACpC,QAAM,MAAM,KAAK,MAAM,GAAG,QAAQ;AAClC,QAAM,YAAY,IAAI,YAAY,GAAG;AACrC,SAAO,IAAI,YAAY,WAAW,MAAM,IAAI,MAAM,GAAG,SAAS,IAAI,KAAK,QAAQ,CAAC;AACpF;AAKO,IAAM,eAAN,MAAmB;AAAA,EAItB,YAAY,QAAuB;AAC/B,SAAK,SAAS;AACd,SAAK,UAAU,OAAO,WAAW;AAAA,EACrC;AAAA,EAEA,MAAc,QACV,UACA,UAAuB,CAAC,GACd;AACV,UAAM,MAAM,GAAG,KAAK,OAAO,GAAG,QAAQ;AAEtC,UAAM,UAAkC;AAAA,MACpC,gBAAgB;AAAA,MAChB,GAAI,QAAQ,WAAqC,CAAC;AAAA,IACtD;AAEA,QAAI,KAAK,OAAO,QAAQ;AACpB,cAAQ,iBAAiB,IAAI,KAAK,OAAO;AAAA,IAC7C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AA,MACX;AAAA,IACJ,CAAC;AAGD,UAAM,QAAQ,IAAI,aAAa,QAAQ,IAAI,OAAK,KAAK,OAAO,EAAE,EAAE,CAAC,CAAC;AAElE,WAAO,EAAE,SAAS,aAAa,QAAQ,OAAO;AAAA,EAClD;AACJ;AAEO,SAAS,mBAAmB,QAAqC;AACpE,SAAO,IAAI,aAAa,MAAM;AAClC;","names":["lines"]}
|
package/dist/memory/index.mjs
CHANGED
|
@@ -1,4 +1,26 @@
|
|
|
1
1
|
// src/memory/index.ts
|
|
2
|
+
var MEMORY_FETCH_TOOL = {
|
|
3
|
+
type: "function",
|
|
4
|
+
function: {
|
|
5
|
+
name: "memory_fetch",
|
|
6
|
+
description: "Fetch the full content of a stored memory by its id (shown in the memory index). Only call this for memories whose summary is relevant to the current request; do not fetch memories you do not need.",
|
|
7
|
+
parameters: {
|
|
8
|
+
type: "object",
|
|
9
|
+
properties: {
|
|
10
|
+
id: { type: "string", description: 'The memory id from the memory index, e.g. "mem_abc123".' }
|
|
11
|
+
},
|
|
12
|
+
required: ["id"],
|
|
13
|
+
additionalProperties: false
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
function summarizeMemory(content, maxChars = 100) {
|
|
18
|
+
const flat = content.replace(/\s+/g, " ").trim();
|
|
19
|
+
if (flat.length <= maxChars) return flat;
|
|
20
|
+
const cut = flat.slice(0, maxChars);
|
|
21
|
+
const lastSpace = cut.lastIndexOf(" ");
|
|
22
|
+
return `${(lastSpace > maxChars * 0.6 ? cut.slice(0, lastSpace) : cut).trimEnd()}\u2026`;
|
|
23
|
+
}
|
|
2
24
|
var MemoryClient = class {
|
|
3
25
|
constructor(config) {
|
|
4
26
|
this.config = config;
|
|
@@ -82,6 +104,75 @@ var MemoryClient = class {
|
|
|
82
104
|
if (options.cursor) params.set("cursor", options.cursor);
|
|
83
105
|
return this.request(`/v1/memory/list?${params.toString()}`);
|
|
84
106
|
}
|
|
107
|
+
/**
|
|
108
|
+
* Suggest memories worth forgetting — stale, low-strength, long-idle
|
|
109
|
+
* candidates (never auto-deleted). Review, then `forget(id)` the ones you
|
|
110
|
+
* want gone. The product never silently forgets a user's memories.
|
|
111
|
+
*
|
|
112
|
+
* @example
|
|
113
|
+
* ```typescript
|
|
114
|
+
* const { suggestions } = await cencori.memory.forgetSuggestions({ userId });
|
|
115
|
+
* for (const s of suggestions) await cencori.memory.forget(s.id);
|
|
116
|
+
* ```
|
|
117
|
+
*/
|
|
118
|
+
async forgetSuggestions(options) {
|
|
119
|
+
const params = new URLSearchParams();
|
|
120
|
+
if (options.userId) params.set("userId", options.userId);
|
|
121
|
+
if (options.sessionId) params.set("sessionId", options.sessionId);
|
|
122
|
+
if (options.scope) params.set("scope", options.scope);
|
|
123
|
+
if (options.namespace) params.set("namespace", options.namespace);
|
|
124
|
+
if (options.limit) params.set("limit", String(options.limit));
|
|
125
|
+
if (options.minIdleDays != null) params.set("minIdleDays", String(options.minIdleDays));
|
|
126
|
+
return this.request(`/v1/memory/forget-suggestions?${params.toString()}`);
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Extract entities + relations from an exchange and add them to the user's
|
|
130
|
+
* memory graph (Layer 5). Enables multi-hop recall — "who does Sarah report
|
|
131
|
+
* to, and where do they work?".
|
|
132
|
+
*
|
|
133
|
+
* @example
|
|
134
|
+
* ```typescript
|
|
135
|
+
* await cencori.memory.rememberGraph({ userId, user: message, assistant: reply });
|
|
136
|
+
* ```
|
|
137
|
+
*/
|
|
138
|
+
async rememberGraph(options) {
|
|
139
|
+
return this.request("/v1/memory/graph", {
|
|
140
|
+
method: "POST",
|
|
141
|
+
body: JSON.stringify(options)
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Traverse the memory graph outward from an entity, returning connected
|
|
146
|
+
* entities and the relations linking them.
|
|
147
|
+
*
|
|
148
|
+
* @example
|
|
149
|
+
* ```typescript
|
|
150
|
+
* const { nodes, edges } = await cencori.memory.graph({ userId, entity: 'Sarah', hops: 2 });
|
|
151
|
+
* ```
|
|
152
|
+
*/
|
|
153
|
+
async graph(options) {
|
|
154
|
+
const params = new URLSearchParams();
|
|
155
|
+
if (options.userId) params.set("userId", options.userId);
|
|
156
|
+
if (options.sessionId) params.set("sessionId", options.sessionId);
|
|
157
|
+
if (options.scope) params.set("scope", options.scope);
|
|
158
|
+
if (options.namespace) params.set("namespace", options.namespace);
|
|
159
|
+
params.set("entity", options.entity);
|
|
160
|
+
if (options.hops != null) params.set("hops", String(options.hops));
|
|
161
|
+
return this.request(`/v1/memory/graph?${params.toString()}`);
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* List the entities in a user's memory graph (most-mentioned first).
|
|
165
|
+
*/
|
|
166
|
+
async entities(options) {
|
|
167
|
+
const params = new URLSearchParams();
|
|
168
|
+
if (options.userId) params.set("userId", options.userId);
|
|
169
|
+
if (options.sessionId) params.set("sessionId", options.sessionId);
|
|
170
|
+
if (options.scope) params.set("scope", options.scope);
|
|
171
|
+
if (options.namespace) params.set("namespace", options.namespace);
|
|
172
|
+
if (options.type) params.set("type", options.type);
|
|
173
|
+
if (options.limit != null) params.set("limit", String(options.limit));
|
|
174
|
+
return this.request(`/v1/memory/entities?${params.toString()}`);
|
|
175
|
+
}
|
|
85
176
|
/**
|
|
86
177
|
* Recall — search a user's memories and return an inject-ready system
|
|
87
178
|
* string. The provider-agnostic read path: drop the result into your own
|
|
@@ -108,9 +199,20 @@ var MemoryClient = class {
|
|
|
108
199
|
query,
|
|
109
200
|
topK: options.topK,
|
|
110
201
|
threshold: options.threshold,
|
|
111
|
-
namespace: options.namespace
|
|
202
|
+
namespace: options.namespace,
|
|
203
|
+
asOf: options.asOf,
|
|
204
|
+
graph: options.graph
|
|
112
205
|
});
|
|
113
206
|
if (results.length === 0) return "";
|
|
207
|
+
if (options.mode === "index") {
|
|
208
|
+
const lines2 = results.map((m) => `- [${m.id}] ${summarizeMemory(m.content)}`);
|
|
209
|
+
return [
|
|
210
|
+
"Memory index \u2014 what you know about this user (summaries only):",
|
|
211
|
+
...lines2,
|
|
212
|
+
"",
|
|
213
|
+
"Each line is a stored memory: [id] summary. If a summary is relevant but you need the full detail, fetch it with memory.fetch(id). Do not reveal this index unless the user asks what you know about them."
|
|
214
|
+
].join("\n");
|
|
215
|
+
}
|
|
114
216
|
const lines = results.map((m) => `- ${m.content}`);
|
|
115
217
|
return [
|
|
116
218
|
"Facts about this user (from previous interactions):",
|
|
@@ -119,6 +221,19 @@ var MemoryClient = class {
|
|
|
119
221
|
"Use these facts when they are relevant to the request. Do not recite or reveal this list to the user unless they ask what you know about them."
|
|
120
222
|
].join("\n");
|
|
121
223
|
}
|
|
224
|
+
/**
|
|
225
|
+
* Fetch one scoped memory's full content by id — the "pull the full note"
|
|
226
|
+
* half of index-mode recall. Scoped to your project; a foreign id 404s.
|
|
227
|
+
* (`get` is the legacy namespace store; `fetch` is the /v1 scoped store.)
|
|
228
|
+
*
|
|
229
|
+
* @example
|
|
230
|
+
* ```typescript
|
|
231
|
+
* const memory = await cencori.memory.fetch('mem_abc123');
|
|
232
|
+
* ```
|
|
233
|
+
*/
|
|
234
|
+
async fetch(id) {
|
|
235
|
+
return this.request(`/v1/memory/${id}`);
|
|
236
|
+
}
|
|
122
237
|
/**
|
|
123
238
|
* Remember — hand us a completed {user, assistant} exchange and we extract
|
|
124
239
|
* the durable facts and persist them (redacted, org-isolated). The
|
|
@@ -250,6 +365,7 @@ function createMemoryClient(config) {
|
|
|
250
365
|
return new MemoryClient(config);
|
|
251
366
|
}
|
|
252
367
|
export {
|
|
368
|
+
MEMORY_FETCH_TOOL,
|
|
253
369
|
MemoryClient,
|
|
254
370
|
createMemoryClient
|
|
255
371
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/memory/index.ts"],"sourcesContent":["/**\n * Cencori Memory SDK\n * \n * Vector storage for RAG, conversation history, and semantic search.\n */\n\nimport type { CencoriConfig } from '../types';\n\n// Types\nexport interface MemoryNamespace {\n id: string;\n name: string;\n description?: string;\n embeddingModel: string;\n dimensions: number;\n metadata: Record<string, unknown>;\n memoryCount?: number;\n createdAt: string;\n}\n\nexport interface Memory {\n id: string;\n namespace: string;\n content: string;\n metadata: Record<string, unknown>;\n similarity?: number;\n expiresAt?: string;\n createdAt: string;\n updatedAt?: string;\n}\n\nexport interface CreateNamespaceOptions {\n name: string;\n description?: string;\n embeddingModel?: string;\n dimensions?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface StoreMemoryOptions {\n namespace: string;\n content: string;\n embedding?: number[];\n metadata?: Record<string, unknown>;\n expiresAt?: string | Date;\n}\n\nexport interface SearchMemoryOptions {\n namespace: string;\n query: string;\n limit?: number;\n threshold?: number;\n filter?: Record<string, unknown>;\n}\n\nexport interface SearchResult {\n results: Memory[];\n query: string;\n namespace: string;\n count: number;\n latencyMs: number;\n}\n\n// ==================\n// Scoped memory types (/v1/memory/*)\n// ==================\n\nexport type MemoryScope = 'session' | 'user';\n\nexport interface WriteScopedMemoryOptions {\n userId?: string;\n sessionId?: string;\n scope?: MemoryScope;\n content: string;\n namespace?: string;\n metadata?: Record<string, unknown>;\n importance?: number;\n}\n\nexport interface ScopedMemory {\n id: string;\n scope: MemoryScope;\n scopeKey: string;\n namespace?: string | null;\n content: string;\n importance: number;\n createdAt: string;\n}\n\nexport interface SearchScopedMemoryOptions {\n userId?: string;\n sessionId?: string;\n scope?: MemoryScope;\n query: string;\n topK?: number;\n threshold?: number;\n namespace?: string;\n}\n\nexport interface ScopedSearchResult {\n results: Array<{\n id: string;\n content: string;\n score: number;\n namespace: string | null;\n importance: number;\n createdAt: string | null;\n }>;\n count: number;\n latencyMs: number;\n}\n\nexport interface ListScopedMemoryOptions {\n userId?: string;\n sessionId?: string;\n scope?: MemoryScope;\n namespace?: string;\n limit?: number;\n cursor?: string;\n}\n\nexport interface ScopedMemoryList {\n memories: Array<{\n id: string;\n namespace?: string | null;\n content: string;\n metadata?: Record<string, unknown>;\n importance: number;\n accessCount?: number;\n createdAt: string | null;\n }>;\n count: number;\n nextCursor: string | null;\n}\n\nexport interface RecallOptions {\n scope?: MemoryScope;\n sessionId?: string;\n namespace?: string;\n topK?: number;\n threshold?: number;\n}\n\nexport interface RememberExchange {\n user?: string;\n assistant?: string;\n}\n\nexport interface RememberOptions {\n scope?: MemoryScope;\n sessionId?: string;\n namespace?: string;\n extract?: { model?: string; prompt?: string; minImportance?: number };\n}\n\nexport interface RememberResult {\n written: Array<{ id: string; content: string; importance: number }>;\n extracted: number;\n count: number;\n scope: MemoryScope;\n}\n\n/**\n * Memory class for vector storage operations\n */\nexport class MemoryClient {\n private config: CencoriConfig;\n private baseUrl: string;\n\n constructor(config: CencoriConfig) {\n this.config = config;\n this.baseUrl = config.baseUrl || 'https://cencori.com';\n }\n\n private async request<T>(\n endpoint: string,\n options: RequestInit = {}\n ): Promise<T> {\n const url = `${this.baseUrl}${endpoint}`;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...(options.headers as Record<string, string> || {}),\n };\n\n if (this.config.apiKey) {\n headers['CENCORI_API_KEY'] = this.config.apiKey;\n }\n\n const response = await fetch(url, {\n ...options,\n headers,\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new Error(error.message || `Request failed: ${response.status}`);\n }\n\n return response.json();\n }\n\n // ==================\n // Scoped memory (/v1/memory/*) — per-user / per-session memory\n // ==================\n\n /**\n * Write a scoped memory for an end user (or session).\n *\n * @example\n * ```typescript\n * await cencori.memory.write({\n * userId: session.user.id,\n * content: 'Prefers dark mode. Uses TypeScript primarily.',\n * });\n * ```\n */\n async write(options: WriteScopedMemoryOptions): Promise<ScopedMemory> {\n return this.request<ScopedMemory>('/v1/memory/write', {\n method: 'POST',\n body: JSON.stringify(options),\n });\n }\n\n /**\n * Semantic search over an end user's memories.\n *\n * @example\n * ```typescript\n * const memories = await cencori.memory.searchUser({\n * userId: session.user.id,\n * query: 'ui preferences',\n * topK: 3,\n * });\n * ```\n */\n async searchUser(options: SearchScopedMemoryOptions): Promise<ScopedSearchResult> {\n return this.request<ScopedSearchResult>('/v1/memory/search', {\n method: 'POST',\n body: JSON.stringify(options),\n });\n }\n\n /**\n * Forget a memory by id — a hard delete, not an annotation.\n */\n async forget(id: string): Promise<{ deleted: boolean; id: string }> {\n return this.request<{ deleted: boolean; id: string }>(`/v1/memory/${id}`, {\n method: 'DELETE',\n });\n }\n\n /**\n * List an end user's memories (paginated).\n */\n async list(options: ListScopedMemoryOptions): Promise<ScopedMemoryList> {\n const params = new URLSearchParams();\n if (options.userId) params.set('userId', options.userId);\n if (options.sessionId) params.set('sessionId', options.sessionId);\n if (options.scope) params.set('scope', options.scope);\n if (options.namespace) params.set('namespace', options.namespace);\n if (options.limit) params.set('limit', String(options.limit));\n if (options.cursor) params.set('cursor', options.cursor);\n\n return this.request<ScopedMemoryList>(`/v1/memory/list?${params.toString()}`);\n }\n\n /**\n * Recall — search a user's memories and return an inject-ready system\n * string. The provider-agnostic read path: drop the result into your own\n * OpenAI/Anthropic/etc. call as a system message. Returns '' when there's\n * nothing relevant yet.\n *\n * @example\n * ```typescript\n * const context = await cencori.memory.recall(userId, userMessage);\n * const reply = await openai.chat.completions.create({\n * model: 'gpt-4o',\n * messages: [\n * ...(context ? [{ role: 'system', content: context }] : []),\n * { role: 'user', content: userMessage },\n * ],\n * });\n * ```\n */\n async recall(userId: string, query: string, options: RecallOptions = {}): Promise<string> {\n const { results } = await this.searchUser({\n userId,\n sessionId: options.sessionId,\n scope: options.scope ?? 'user',\n query,\n topK: options.topK,\n threshold: options.threshold,\n namespace: options.namespace,\n });\n\n if (results.length === 0) return '';\n\n const lines = results.map((m) => `- ${m.content}`);\n return [\n 'Facts about this user (from previous interactions):',\n ...lines,\n '',\n 'Use these facts when they are relevant to the request. Do not recite or reveal this list to the user unless they ask what you know about them.',\n ].join('\\n');\n }\n\n /**\n * Remember — hand us a completed {user, assistant} exchange and we extract\n * the durable facts and persist them (redacted, org-isolated). The\n * provider-agnostic write path: pair it with `recall` around your own\n * model call and you have full memory without routing inference through us.\n *\n * @example\n * ```typescript\n * await cencori.memory.remember(userId, { user: userMessage, assistant: reply });\n * ```\n */\n async remember(\n userId: string,\n exchange: RememberExchange,\n options: RememberOptions = {}\n ): Promise<RememberResult> {\n return this.request<RememberResult>('/v1/memory/remember', {\n method: 'POST',\n body: JSON.stringify({\n userId,\n sessionId: options.sessionId,\n scope: options.scope ?? 'user',\n namespace: options.namespace,\n user: exchange.user,\n assistant: exchange.assistant,\n extract: options.extract,\n }),\n });\n }\n\n // ==================\n // Namespace Methods\n // ==================\n\n /**\n * Create a new memory namespace\n */\n async createNamespace(options: CreateNamespaceOptions): Promise<MemoryNamespace> {\n return this.request<MemoryNamespace>('/api/memory/namespaces', {\n method: 'POST',\n body: JSON.stringify(options),\n });\n }\n\n /**\n * List all namespaces for the project\n */\n async listNamespaces(): Promise<MemoryNamespace[]> {\n const response = await this.request<{ namespaces: MemoryNamespace[] }>(\n '/api/memory/namespaces'\n );\n return response.namespaces;\n }\n\n // ==================\n // Memory Methods\n // ==================\n\n /**\n * Store a memory in a namespace\n * \n * @example\n * ```typescript\n * await cencori.memory.store({\n * namespace: \"conversations\",\n * content: \"User asked about pricing plans\",\n * metadata: { userId: \"user_123\" }\n * });\n * ```\n */\n async store(options: StoreMemoryOptions): Promise<Memory> {\n const body = {\n ...options,\n expiresAt: options.expiresAt instanceof Date\n ? options.expiresAt.toISOString()\n : options.expiresAt,\n };\n\n return this.request<Memory>('/api/memory/store', {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n /**\n * Semantic search across memories\n * \n * @example\n * ```typescript\n * const results = await cencori.memory.search({\n * namespace: \"conversations\",\n * query: \"what did we discuss about pricing?\",\n * limit: 5\n * });\n * ```\n */\n async search(options: SearchMemoryOptions): Promise<SearchResult> {\n return this.request<SearchResult>('/api/memory/search', {\n method: 'POST',\n body: JSON.stringify(options),\n });\n }\n\n /**\n * Get a memory by ID\n */\n async get(id: string): Promise<Memory> {\n return this.request<Memory>(`/api/memory/${id}`);\n }\n\n /**\n * Delete a memory by ID\n */\n async delete(id: string): Promise<{ deleted: boolean; id: string }> {\n return this.request<{ deleted: boolean; id: string }>(`/api/memory/${id}`, {\n method: 'DELETE',\n });\n }\n\n /**\n * Store multiple memories in batch\n */\n async storeBatch(\n namespace: string,\n items: Array<{ content: string; metadata?: Record<string, unknown> }>\n ): Promise<Memory[]> {\n const results = await Promise.all(\n items.map(item => this.store({ namespace, ...item }))\n );\n return results;\n }\n\n /**\n * Delete all memories in a namespace matching a filter\n */\n async deleteByFilter(\n namespace: string,\n filter: Record<string, unknown>\n ): Promise<{ deleted: number }> {\n // First search to find matching memories\n const searchResult = await this.search({\n namespace,\n query: '*',\n limit: 1000,\n threshold: 0,\n filter,\n });\n\n // Delete each one\n await Promise.all(searchResult.results.map(r => this.delete(r.id)));\n\n return { deleted: searchResult.results.length };\n }\n}\n\nexport function createMemoryClient(config: CencoriConfig): MemoryClient {\n return new MemoryClient(config);\n}\n"],"mappings":";AAqKO,IAAM,eAAN,MAAmB;AAAA,EAItB,YAAY,QAAuB;AAC/B,SAAK,SAAS;AACd,SAAK,UAAU,OAAO,WAAW;AAAA,EACrC;AAAA,EAEA,MAAc,QACV,UACA,UAAuB,CAAC,GACd;AACV,UAAM,MAAM,GAAG,KAAK,OAAO,GAAG,QAAQ;AAEtC,UAAM,UAAkC;AAAA,MACpC,gBAAgB;AAAA,MAChB,GAAI,QAAQ,WAAqC,CAAC;AAAA,IACtD;AAEA,QAAI,KAAK,OAAO,QAAQ;AACpB,cAAQ,iBAAiB,IAAI,KAAK,OAAO;AAAA,IAC7C;AAEA,UAAM,WAAW,MAAM,MAAM,KAAK;AAAA,MAC9B,GAAG;AAAA,MACH;AAAA,IACJ,CAAC;AAED,QAAI,CAAC,SAAS,IAAI;AACd,YAAM,QAAQ,MAAM,SAAS,KAAK,EAAE,MAAM,OAAO,CAAC,EAAE;AACpD,YAAM,IAAI,MA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A,MACX;AAAA,IACJ,CAAC;AAGD,UAAM,QAAQ,IAAI,aAAa,QAAQ,IAAI,OAAK,KAAK,OAAO,EAAE,EAAE,CAAC,CAAC;AAElE,WAAO,EAAE,SAAS,aAAa,QAAQ,OAAO;AAAA,EAClD;AACJ;AAEO,SAAS,mBAAmB,QAAqC;AACpE,SAAO,IAAI,aAAa,MAAM;AAClC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/memory/index.ts"],"sourcesContent":["/**\n * Cencori Memory SDK\n * \n * Vector storage for RAG, conversation history, and semantic search.\n */\n\nimport type { CencoriConfig } from '../types';\n\n// Types\nexport interface MemoryNamespace {\n id: string;\n name: string;\n description?: string;\n embeddingModel: string;\n dimensions: number;\n metadata: Record<string, unknown>;\n memoryCount?: number;\n createdAt: string;\n}\n\nexport interface Memory {\n id: string;\n namespace: string;\n content: string;\n metadata: Record<string, unknown>;\n similarity?: number;\n expiresAt?: string;\n createdAt: string;\n updatedAt?: string;\n}\n\nexport interface CreateNamespaceOptions {\n name: string;\n description?: string;\n embeddingModel?: string;\n dimensions?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface StoreMemoryOptions {\n namespace: string;\n content: string;\n embedding?: number[];\n metadata?: Record<string, unknown>;\n expiresAt?: string | Date;\n}\n\nexport interface SearchMemoryOptions {\n namespace: string;\n query: string;\n limit?: number;\n threshold?: number;\n filter?: Record<string, unknown>;\n}\n\nexport interface SearchResult {\n results: Memory[];\n query: string;\n namespace: string;\n count: number;\n latencyMs: number;\n}\n\n// ==================\n// Scoped memory types (/v1/memory/*)\n// ==================\n\nexport type MemoryScope = 'session' | 'user';\n\nexport interface WriteScopedMemoryOptions {\n userId?: string;\n sessionId?: string;\n scope?: MemoryScope;\n content: string;\n namespace?: string;\n metadata?: Record<string, unknown>;\n importance?: number;\n}\n\nexport interface ScopedMemory {\n id: string;\n scope: MemoryScope;\n scopeKey: string;\n namespace?: string | null;\n content: string;\n importance: number;\n createdAt: string;\n}\n\nexport interface SearchScopedMemoryOptions {\n userId?: string;\n sessionId?: string;\n scope?: MemoryScope;\n query: string;\n topK?: number;\n threshold?: number;\n namespace?: string;\n /**\n * Temporal recall: search memory as it was valid at this instant (ISO 8601),\n * including facts later superseded. Omit for current state.\n */\n asOf?: string;\n /**\n * Graph-aware recall (default true): when the query names an entity we know,\n * also walk its relations and return facts about the connected entities that\n * similarity alone would miss. Set false for strictly vector search.\n */\n graph?: boolean;\n}\n\nexport interface ScopedSearchResult {\n results: Array<{\n id: string;\n content: string;\n /** Cosine similarity, or 0 for a memory reached across the graph. */\n score: number;\n namespace: string | null;\n importance: number;\n createdAt: string | null;\n /** 'vector' (matched), 'graph' (walked to), or 'session'. */\n source?: 'vector' | 'graph' | 'session';\n /** Hops from the query's entity, for graph-reached memories. */\n hops?: number;\n }>;\n count: number;\n latencyMs: number;\n}\n\nexport interface ListScopedMemoryOptions {\n userId?: string;\n sessionId?: string;\n scope?: MemoryScope;\n namespace?: string;\n limit?: number;\n cursor?: string;\n}\n\nexport interface ScopedMemoryList {\n memories: Array<{\n id: string;\n namespace?: string | null;\n content: string;\n metadata?: Record<string, unknown>;\n importance: number;\n accessCount?: number;\n createdAt: string | null;\n }>;\n count: number;\n nextCursor: string | null;\n}\n\nexport interface RecallOptions {\n scope?: MemoryScope;\n sessionId?: string;\n namespace?: string;\n topK?: number;\n threshold?: number;\n /** Temporal recall: memory as it was valid at this instant (ISO 8601). */\n asOf?: string;\n /**\n * Graph-aware recall (default true): also walk the entity graph from the\n * entities the query names, pulling in connected facts.\n */\n graph?: boolean;\n /**\n * 'inject' (default) returns an inject-ready block of full memory contents.\n * 'index' returns a compact table of contents (`- [id] summary`) — fetch a\n * full note with `memory.fetch(id)` when the summary is relevant.\n */\n mode?: 'inject' | 'index';\n}\n\nexport interface RememberExchange {\n user?: string;\n assistant?: string;\n}\n\nexport interface RememberOptions {\n scope?: MemoryScope;\n sessionId?: string;\n namespace?: string;\n extract?: { model?: string; prompt?: string; minImportance?: number };\n}\n\nexport interface RememberResult {\n written: Array<{ id: string; content: string; importance: number }>;\n extracted: number;\n count: number;\n scope: MemoryScope;\n}\n\nexport interface ForgetSuggestionsOptions {\n userId?: string;\n sessionId?: string;\n scope?: MemoryScope;\n namespace?: string;\n /** Max suggestions (weakest first). Default 20. */\n limit?: number;\n /** Only suggest memories not used in at least this many days. Default 60. */\n minIdleDays?: number;\n}\n\nexport interface ForgetSuggestionsResult {\n suggestions: Array<{\n id: string;\n content: string;\n /** Query-independent durability score, 0–1 (lower = safer to forget). */\n strength: number;\n idleDays: number;\n importance: number;\n }>;\n count: number;\n /** How many active memories were evaluated. */\n evaluated: number;\n}\n\n// ── Entity graph (Layer 5) ──\nexport interface RememberGraphOptions {\n userId?: string;\n sessionId?: string;\n scope?: MemoryScope;\n namespace?: string;\n user?: string;\n assistant?: string;\n}\n\nexport interface RememberGraphResult {\n entities: number;\n created: number;\n merged: number;\n relations: number;\n costUsd: number;\n}\n\nexport interface GraphQueryOptions {\n userId?: string;\n sessionId?: string;\n scope?: MemoryScope;\n namespace?: string;\n /** Entity name to start the traversal from. */\n entity: string;\n /** How many hops outward (1–4). Default 2. */\n hops?: number;\n}\n\nexport interface GraphResult {\n seed: { id: string; name: string; type: string } | null;\n nodes: Array<{ id: string; name: string; type: string; hops: number; path: string[] }>;\n edges: Array<{ source: string; relation: string; target: string }>;\n message?: string;\n}\n\nexport interface ListEntitiesOptions {\n userId?: string;\n sessionId?: string;\n scope?: MemoryScope;\n namespace?: string;\n type?: string;\n limit?: number;\n}\n\nexport interface EntitiesResult {\n entities: Array<{\n id: string;\n name: string;\n type: string;\n aliases: string[];\n mentionCount: number;\n createdAt: string;\n }>;\n count: number;\n}\n\n/** Full memory returned by `memory.fetch(id)` / GET /v1/memory/:id. */\nexport interface FetchedMemory {\n id: string;\n scope: MemoryScope;\n scopeKey: string;\n namespace: string | null;\n content: string;\n metadata?: Record<string, unknown>;\n importance: number;\n accessCount?: number;\n lastAccessedAt?: string | null;\n expiresAt?: string | null;\n createdAt: string | null;\n updatedAt?: string | null;\n}\n\n/**\n * Function-tool schema for index-mode agents. Register it in your `tools` so the\n * model can pull a full memory by id (from the recall index) on demand, then\n * resolve the call with `memory.fetch(id)`.\n *\n * @example\n * ```typescript\n * tools: [MEMORY_FETCH_TOOL]\n * // when the model calls memory_fetch({ id }): const m = await cencori.memory.fetch(id);\n * ```\n */\nexport const MEMORY_FETCH_TOOL = {\n type: 'function',\n function: {\n name: 'memory_fetch',\n description:\n 'Fetch the full content of a stored memory by its id (shown in the memory index). Only call this for memories whose summary is relevant to the current request; do not fetch memories you do not need.',\n parameters: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'The memory id from the memory index, e.g. \"mem_abc123\".' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n} as const;\n\n/** One-line summary of a memory for the index/TOC (whitespace-collapse + truncate). */\nfunction summarizeMemory(content: string, maxChars = 100): string {\n const flat = content.replace(/\\s+/g, ' ').trim();\n if (flat.length <= maxChars) return flat;\n const cut = flat.slice(0, maxChars);\n const lastSpace = cut.lastIndexOf(' ');\n return `${(lastSpace > maxChars * 0.6 ? cut.slice(0, lastSpace) : cut).trimEnd()}…`;\n}\n\n/**\n * Memory class for vector storage operations\n */\nexport class MemoryClient {\n private config: CencoriConfig;\n private baseUrl: string;\n\n constructor(config: CencoriConfig) {\n this.config = config;\n this.baseUrl = config.baseUrl || 'https://cencori.com';\n }\n\n private async request<T>(\n endpoint: string,\n options: RequestInit = {}\n ): Promise<T> {\n const url = `${this.baseUrl}${endpoint}`;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...(options.headers as Record<string, string> || {}),\n };\n\n if (this.config.apiKey) {\n headers['CENCORI_API_KEY'] = this.config.apiKey;\n }\n\n const response = await fetch(url, {\n ...options,\n headers,\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new Error(error.message || `Request failed: ${response.status}`);\n }\n\n return response.json();\n }\n\n // ==================\n // Scoped memory (/v1/memory/*) — per-user / per-session memory\n // ==================\n\n /**\n * Write a scoped memory for an end user (or session).\n *\n * @example\n * ```typescript\n * await cencori.memory.write({\n * userId: session.user.id,\n * content: 'Prefers dark mode. Uses TypeScript primarily.',\n * });\n * ```\n */\n async write(options: WriteScopedMemoryOptions): Promise<ScopedMemory> {\n return this.request<ScopedMemory>('/v1/memory/write', {\n method: 'POST',\n body: JSON.stringify(options),\n });\n }\n\n /**\n * Semantic search over an end user's memories.\n *\n * @example\n * ```typescript\n * const memories = await cencori.memory.searchUser({\n * userId: session.user.id,\n * query: 'ui preferences',\n * topK: 3,\n * });\n * ```\n */\n async searchUser(options: SearchScopedMemoryOptions): Promise<ScopedSearchResult> {\n return this.request<ScopedSearchResult>('/v1/memory/search', {\n method: 'POST',\n body: JSON.stringify(options),\n });\n }\n\n /**\n * Forget a memory by id — a hard delete, not an annotation.\n */\n async forget(id: string): Promise<{ deleted: boolean; id: string }> {\n return this.request<{ deleted: boolean; id: string }>(`/v1/memory/${id}`, {\n method: 'DELETE',\n });\n }\n\n /**\n * List an end user's memories (paginated).\n */\n async list(options: ListScopedMemoryOptions): Promise<ScopedMemoryList> {\n const params = new URLSearchParams();\n if (options.userId) params.set('userId', options.userId);\n if (options.sessionId) params.set('sessionId', options.sessionId);\n if (options.scope) params.set('scope', options.scope);\n if (options.namespace) params.set('namespace', options.namespace);\n if (options.limit) params.set('limit', String(options.limit));\n if (options.cursor) params.set('cursor', options.cursor);\n\n return this.request<ScopedMemoryList>(`/v1/memory/list?${params.toString()}`);\n }\n\n /**\n * Suggest memories worth forgetting — stale, low-strength, long-idle\n * candidates (never auto-deleted). Review, then `forget(id)` the ones you\n * want gone. The product never silently forgets a user's memories.\n *\n * @example\n * ```typescript\n * const { suggestions } = await cencori.memory.forgetSuggestions({ userId });\n * for (const s of suggestions) await cencori.memory.forget(s.id);\n * ```\n */\n async forgetSuggestions(options: ForgetSuggestionsOptions): Promise<ForgetSuggestionsResult> {\n const params = new URLSearchParams();\n if (options.userId) params.set('userId', options.userId);\n if (options.sessionId) params.set('sessionId', options.sessionId);\n if (options.scope) params.set('scope', options.scope);\n if (options.namespace) params.set('namespace', options.namespace);\n if (options.limit) params.set('limit', String(options.limit));\n if (options.minIdleDays != null) params.set('minIdleDays', String(options.minIdleDays));\n\n return this.request<ForgetSuggestionsResult>(`/v1/memory/forget-suggestions?${params.toString()}`);\n }\n\n /**\n * Extract entities + relations from an exchange and add them to the user's\n * memory graph (Layer 5). Enables multi-hop recall — \"who does Sarah report\n * to, and where do they work?\".\n *\n * @example\n * ```typescript\n * await cencori.memory.rememberGraph({ userId, user: message, assistant: reply });\n * ```\n */\n async rememberGraph(options: RememberGraphOptions): Promise<RememberGraphResult> {\n return this.request<RememberGraphResult>('/v1/memory/graph', {\n method: 'POST',\n body: JSON.stringify(options),\n });\n }\n\n /**\n * Traverse the memory graph outward from an entity, returning connected\n * entities and the relations linking them.\n *\n * @example\n * ```typescript\n * const { nodes, edges } = await cencori.memory.graph({ userId, entity: 'Sarah', hops: 2 });\n * ```\n */\n async graph(options: GraphQueryOptions): Promise<GraphResult> {\n const params = new URLSearchParams();\n if (options.userId) params.set('userId', options.userId);\n if (options.sessionId) params.set('sessionId', options.sessionId);\n if (options.scope) params.set('scope', options.scope);\n if (options.namespace) params.set('namespace', options.namespace);\n params.set('entity', options.entity);\n if (options.hops != null) params.set('hops', String(options.hops));\n return this.request<GraphResult>(`/v1/memory/graph?${params.toString()}`);\n }\n\n /**\n * List the entities in a user's memory graph (most-mentioned first).\n */\n async entities(options: ListEntitiesOptions): Promise<EntitiesResult> {\n const params = new URLSearchParams();\n if (options.userId) params.set('userId', options.userId);\n if (options.sessionId) params.set('sessionId', options.sessionId);\n if (options.scope) params.set('scope', options.scope);\n if (options.namespace) params.set('namespace', options.namespace);\n if (options.type) params.set('type', options.type);\n if (options.limit != null) params.set('limit', String(options.limit));\n return this.request<EntitiesResult>(`/v1/memory/entities?${params.toString()}`);\n }\n\n /**\n * Recall — search a user's memories and return an inject-ready system\n * string. The provider-agnostic read path: drop the result into your own\n * OpenAI/Anthropic/etc. call as a system message. Returns '' when there's\n * nothing relevant yet.\n *\n * @example\n * ```typescript\n * const context = await cencori.memory.recall(userId, userMessage);\n * const reply = await openai.chat.completions.create({\n * model: 'gpt-4o',\n * messages: [\n * ...(context ? [{ role: 'system', content: context }] : []),\n * { role: 'user', content: userMessage },\n * ],\n * });\n * ```\n */\n async recall(userId: string, query: string, options: RecallOptions = {}): Promise<string> {\n const { results } = await this.searchUser({\n userId,\n sessionId: options.sessionId,\n scope: options.scope ?? 'user',\n query,\n topK: options.topK,\n threshold: options.threshold,\n namespace: options.namespace,\n asOf: options.asOf,\n graph: options.graph,\n });\n\n if (results.length === 0) return '';\n\n // Index mode: a compact table of contents — fetch full notes with get(id).\n if (options.mode === 'index') {\n const lines = results.map((m) => `- [${m.id}] ${summarizeMemory(m.content)}`);\n return [\n 'Memory index — what you know about this user (summaries only):',\n ...lines,\n '',\n 'Each line is a stored memory: [id] summary. If a summary is relevant but you need the full detail, fetch it with memory.fetch(id). Do not reveal this index unless the user asks what you know about them.',\n ].join('\\n');\n }\n\n const lines = results.map((m) => `- ${m.content}`);\n return [\n 'Facts about this user (from previous interactions):',\n ...lines,\n '',\n 'Use these facts when they are relevant to the request. Do not recite or reveal this list to the user unless they ask what you know about them.',\n ].join('\\n');\n }\n\n /**\n * Fetch one scoped memory's full content by id — the \"pull the full note\"\n * half of index-mode recall. Scoped to your project; a foreign id 404s.\n * (`get` is the legacy namespace store; `fetch` is the /v1 scoped store.)\n *\n * @example\n * ```typescript\n * const memory = await cencori.memory.fetch('mem_abc123');\n * ```\n */\n async fetch(id: string): Promise<FetchedMemory> {\n return this.request<FetchedMemory>(`/v1/memory/${id}`);\n }\n\n /**\n * Remember — hand us a completed {user, assistant} exchange and we extract\n * the durable facts and persist them (redacted, org-isolated). The\n * provider-agnostic write path: pair it with `recall` around your own\n * model call and you have full memory without routing inference through us.\n *\n * @example\n * ```typescript\n * await cencori.memory.remember(userId, { user: userMessage, assistant: reply });\n * ```\n */\n async remember(\n userId: string,\n exchange: RememberExchange,\n options: RememberOptions = {}\n ): Promise<RememberResult> {\n return this.request<RememberResult>('/v1/memory/remember', {\n method: 'POST',\n body: JSON.stringify({\n userId,\n sessionId: options.sessionId,\n scope: options.scope ?? 'user',\n namespace: options.namespace,\n user: exchange.user,\n assistant: exchange.assistant,\n extract: options.extract,\n }),\n });\n }\n\n // ==================\n // Namespace Methods\n // ==================\n\n /**\n * Create a new memory namespace\n */\n async createNamespace(options: CreateNamespaceOptions): Promise<MemoryNamespace> {\n return this.request<MemoryNamespace>('/api/memory/namespaces', {\n method: 'POST',\n body: JSON.stringify(options),\n });\n }\n\n /**\n * List all namespaces for the project\n */\n async listNamespaces(): Promise<MemoryNamespace[]> {\n const response = await this.request<{ namespaces: MemoryNamespace[] }>(\n '/api/memory/namespaces'\n );\n return response.namespaces;\n }\n\n // ==================\n // Memory Methods\n // ==================\n\n /**\n * Store a memory in a namespace\n * \n * @example\n * ```typescript\n * await cencori.memory.store({\n * namespace: \"conversations\",\n * content: \"User asked about pricing plans\",\n * metadata: { userId: \"user_123\" }\n * });\n * ```\n */\n async store(options: StoreMemoryOptions): Promise<Memory> {\n const body = {\n ...options,\n expiresAt: options.expiresAt instanceof Date\n ? options.expiresAt.toISOString()\n : options.expiresAt,\n };\n\n return this.request<Memory>('/api/memory/store', {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n /**\n * Semantic search across memories\n * \n * @example\n * ```typescript\n * const results = await cencori.memory.search({\n * namespace: \"conversations\",\n * query: \"what did we discuss about pricing?\",\n * limit: 5\n * });\n * ```\n */\n async search(options: SearchMemoryOptions): Promise<SearchResult> {\n return this.request<SearchResult>('/api/memory/search', {\n method: 'POST',\n body: JSON.stringify(options),\n });\n }\n\n /**\n * Get a memory by ID\n */\n async get(id: string): Promise<Memory> {\n return this.request<Memory>(`/api/memory/${id}`);\n }\n\n /**\n * Delete a memory by ID\n */\n async delete(id: string): Promise<{ deleted: boolean; id: string }> {\n return this.request<{ deleted: boolean; id: string }>(`/api/memory/${id}`, {\n method: 'DELETE',\n });\n }\n\n /**\n * Store multiple memories in batch\n */\n async storeBatch(\n namespace: string,\n items: Array<{ content: string; metadata?: Record<string, unknown> }>\n ): Promise<Memory[]> {\n const results = await Promise.all(\n items.map(item => this.store({ namespace, ...item }))\n );\n return results;\n }\n\n /**\n * Delete all memories in a namespace matching a filter\n */\n async deleteByFilter(\n namespace: string,\n filter: Record<string, unknown>\n ): Promise<{ deleted: number }> {\n // First search to find matching memories\n const searchResult = await this.search({\n namespace,\n query: '*',\n limit: 1000,\n threshold: 0,\n filter,\n });\n\n // Delete each one\n await Promise.all(searchResult.results.map(r => this.delete(r.id)));\n\n return { deleted: searchResult.results.length };\n }\n}\n\nexport function createMemoryClient(config: CencoriConfig): MemoryClient {\n return new MemoryClient(config);\n}\n"],"mappings":";AA4SO,IAAM,oBAAoB;AAAA,EAC7B,MAAM;AAAA,EACN,UAAU;AAAA,IACN,MAAM;AAAA,IACN,aACI;AAAA,IACJ,YAAY;AAAA,MACR,MAAM;AAAA,MACN,YAAY;AAAA,QACR,IAAI,EAAE,MAAM,UAAU,aAAa,0DAA0D;AAAA,MACjG;AAAA,MACA,UAAU,CAAC,IAAI;AAAA,MACf,sBAAsB;AAAA,IAC1B;AAAA,EACJ;AACJ;AAGA,SAAS,gBAAgB,SAAiB,WAAW,KAAa;AAC9D,QAAM,OAAO,QAAQ,QAAQ,QAAQ,GAAG,EAAE,KAAK;AAC/C,MAAI,KAAK,UAAU,SAAU,QAAO;AACpC,QAAM,MAAM,KAAK,MAAM,GAAG,QAAQ;AAClC,QAAM,YAAY,IAAI,YAAY,GAAG;AACrC,SAAO,IAAI,YAAY,WAAW,MAAM,IAAI,MAAM,GAAG,SAAS,IAAI,KAAK,QAAQ,CAAC;AACpF;AAKO,IAAM,eAAN,MAAmB;AAAA,EAItB,YAAY,QAAuB;AAC/B,SAAK,SAAS;AACd,SAAK,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jB,UAAM,UAAU,MAAM,QAAQ;AAAA,MAC1B,MAAM,IAAI,UAAQ,KAAK,MAAM,EAAE,WAAW,GAAG,KAAK,CAAC,CAAC;AAAA,IACxD;AACA,WAAO;AAAA,EACX;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,eACF,WACA,QAC4B;AAE5B,UAAM,eAAe,MAAM,KAAK,OAAO;AAAA,MACnC;AAAA,MACA,OAAO;AAAA,MACP,OAAO;AAAA,MACP,WAAW;AAAA,MACX;AAAA,IACJ,CAAC;AAGD,UAAM,QAAQ,IAAI,aAAa,QAAQ,IAAI,OAAK,KAAK,OAAO,EAAE,EAAE,CAAC,CAAC;AAElE,WAAO,EAAE,SAAS,aAAa,QAAQ,OAAO;AAAA,EAClD;AACJ;AAEO,SAAS,mBAAmB,QAAqC;AACpE,SAAO,IAAI,aAAa,MAAM;AAClC;","names":["lines"]}
|
package/dist/react/index.d.mts
CHANGED
|
@@ -11,6 +11,10 @@ interface ChatMemoryProp {
|
|
|
11
11
|
topK?: number;
|
|
12
12
|
threshold?: number;
|
|
13
13
|
namespace?: string;
|
|
14
|
+
/** Temporal recall: memory as it was valid at this instant (ISO 8601). */
|
|
15
|
+
asOf?: string;
|
|
16
|
+
/** 'inject' (default) full contents, or 'index' compact table-of-contents. */
|
|
17
|
+
mode?: 'inject' | 'index';
|
|
14
18
|
extract?: {
|
|
15
19
|
model?: string;
|
|
16
20
|
prompt?: string;
|
package/dist/react/index.d.ts
CHANGED
|
@@ -11,6 +11,10 @@ interface ChatMemoryProp {
|
|
|
11
11
|
topK?: number;
|
|
12
12
|
threshold?: number;
|
|
13
13
|
namespace?: string;
|
|
14
|
+
/** Temporal recall: memory as it was valid at this instant (ISO 8601). */
|
|
15
|
+
asOf?: string;
|
|
16
|
+
/** 'inject' (default) full contents, or 'index' compact table-of-contents. */
|
|
17
|
+
mode?: 'inject' | 'index';
|
|
14
18
|
extract?: {
|
|
15
19
|
model?: string;
|
|
16
20
|
prompt?: string;
|