Skip to main content
doc0blade47/mem0documentation home
Sign in

Typescript Core

Last updated Oct 11, 2026
Relevant source files

The following files were used as context for generating this wiki page:

Overview

The TypeScript OSS package provides the fundamental architecture for local and self-hosted memory management within the Mem0 ecosystem. At its center stands the core Memory class, which orchestrates semantic embedding models, Large Language Model (LLM) fact extraction pipelines, vector stores, and relational audit logging. Rather than relying entirely on remote hosted endpoints, the TypeScript core implements a standalone execution engine capable of parsing conversation turns, deduping facts via content hashes, linking related memories through graph references, and enforcing expiration policies.

Sources: mem0-ts/src/oss/src/memory/index.ts:205-211

This subsystem solves the core problem of extracting persistent, contextually rich facts from volatile multi-turn dialogues and maintaining them across agent sessions. By decoupling storage adapters—such as in-memory maps, SQLite databases via better-sqlite3, and Supabase managers—from the memory coordination logic, the engine provides pluggable durability layers. Adjacent components like agent plugins, workflow nodes, and proxy models leverage these APIs to inject dynamic user and agent state into active prompt contexts.

Sources: mem0-ts/src/oss/src/storage/SQLiteManager.ts:1-15

Sources: mem0-ts/src/oss/src/memory/index.ts:1-211, mem0-ts/src/oss/src/config/manager.ts:1-222


TypeScript Client SDK

The TypeScript Client SDK acts as the remote interface layer for communicating with hosted Mem0 platform endpoints or self-hosted HTTP proxy instances. It encapsulates network requests, payload transformations, and client-side telemetry tracking. When interacting with remote services, the client automatically translates user-facing camelCase options into snake_case API payloads while protecting opaque records like metadata and customCategories from unwanted key mutations.

Sources: mem0-ts/src/client/mem0.ts:395-413

const client = new MemoryClient({ apiKey: "your-api-key" });
const searchResults = await client.search("recent project decisions", {
  filters: { userId: "user123" },
  topK: 5,
});

Sources: mem0-ts/src/client/mem0.ts:495-521, mem0-ts/src/client/utils.ts:28-58

The client exposes explicit methods for lifecycle management, including add(), update(), get(), getAll(), search(), delete(), and deleteAll(). To prevent structural errors, top-level entity parameters such as user_id, agent_id, and run_id are rejected if passed directly to search or list methods; instead, callers must nest them inside a filters object. Telemetry events are dispatched asynchronously via PostHog-compatible node fetch wrappers using anonymous distinct IDs initialized from local configuration files stored in ~/.mem0/config.json.

Sources: mem0-ts/src/client/mem0.ts:470-556, mem0-ts/src/client/config.ts:1-96

MethodHTTP ActionEndpoint PathPurpose
addPOST/v3/memories/add/Ingests new messages and triggers extraction
updatePUT/v1/memories/{memoryId}/Modifies existing memory text or metadata
getGET/v1/memories/{memoryId}/Retrieves a single memory item by identifier
getAllPOST/v3/memories/Paginated retrieval under specified filters
searchPOST/v3/memories/search/Semantic and keyword vector store query
deleteDELETE/v1/memories/{memoryId}/Removes a specific memory record
deleteAllDELETE/v1/memories/Purges all memories matching entity scopes

Sources: mem0-ts/src/client/mem0.ts:395-556, mem0-ts/src/client/config.ts:1-96


TypeScript Core Engine

The core engine revolves around the Memory class, which manages configuration state, component factories, and vector operations. Initialization begins through ConfigManager.mergeConfig(), which merges user-supplied overrides with DEFAULT_MEMORY_CONFIG, normalizing parameters across embedders, vector stores, and LLM providers. Entity parameters are strictly validated using helper functions like validateAndTrimEntityId(), ensuring identifiers contain no internal whitespace or empty strings.

Sources: mem0-ts/src/oss/src/memory/index.ts:137-178, mem0-ts/src/oss/src/config/manager.ts:1-222

Sources: mem0-ts/src/oss/src/memory/index.ts:881-1040

When memories are added with infer: true, the engine executes the V3 Additive Extraction pipeline. It first queries existing vector store entries to establish an anti-hallucination UUID-to-integer mapping, retrieves recent session messages from storage, and prompts the LLM using ADDITIVE_EXTRACTION_PROMPT. The response text is cleaned via removeCodeBlocks() and parsed using extractJson(), which handles robust brace and bracket boundary detection for less deterministic local models.

Sources: mem0-ts/src/oss/src/memory/index.ts:918-987, mem0-ts/src/oss/src/prompts/index.ts:901-1042

Warning

Caller metadata must never overwrite or inject identity scopes. The engine invokes stripIdentityKeys() on incoming metadata blobs to strip protected keys (user_id, agent_id, run_id, actor_id) before persisting payloads.

Sources: mem0-ts/src/oss/src/memory/index.ts:108-127


TypeScript History Storage

Persistence of audit logs and conversation session buffers is delegated to implementations of the HistoryManager interface. The core package ships with three primary history managers: DummyHistoryManager (a no-op stub for disabled persistence), MemoryHistoryManager (an in-memory Map implementation), and SQLiteManager (a robust relational manager built on better-sqlite3).

Sources: mem0-ts/src/oss/src/storage/base.ts:1-13, mem0-ts/src/oss/src/storage/MemoryHistoryManager.ts:14-15

export interface HistoryManager {
  addHistory(
    memoryId: string,
    previousValue: string | null,
    newValue: string | null,
    action: string,
    createdAt?: string,
    updatedAt?: string,
    isDeleted?: number,
  ): Promise<void>;
  getHistory(memoryId: string): Promise<any[]>;
  reset(): Promise<void>;
  close(): void;
  saveMessages?(messages: Array<{ role: string; content: string; name?: string }>, sessionScope: string): Promise<void>;
  getLastMessages?(sessionScope: string, limit?: number): Promise<Array<...>>;
}

Sources: mem0-ts/src/oss/src/storage/base.ts:1-37

The SQLiteManager automatically initializes local database directories via ensureSQLiteDirectory() and provisions two core tables: memory_history for tracking mutations (ADD, UPDATE, DELETE) and messages for maintaining bounded conversation buffers per session scope. When saving messages, an eviction query automatically prunes older rows exceeding a sliding window limit of the last 10 messages per session scope inside an atomic transaction. A cloud-backed alternative, SupabaseHistoryManager, provides identical audit capabilities over remote Supabase PostgreSQL instances with automatic table verification.

Sources: mem0-ts/src/oss/src/storage/SQLiteManager.ts:11-108, mem0-ts/src/oss/src/storage/SupabaseHistoryManager.ts:31-74


TypeScript Search Fusion

Retrieval and search ranking within the core package combine dense vector similarity with lexical matching, entity boosting, and temporal expiration filtering. The BM25 utility computes term frequency-inverse document frequency scoring across tokenized memory documents using configurable parameters $k_1$ ($1.5$) and $b$ ($0.75$).

Sources: mem0-ts/src/oss/src/utils/bm25.ts:1-20

export class BM25 {
  private documents: string[][];
  private k1: number;
  private b: number;
  private avgDocLength: number;
  private docFreq: Map<string, number>;
  private docLengths: number[];
  private idf: Map<string, number>;
 
  constructor(documents: string[][], k1 = 1.5, b = 0.75) {
    ...
  }
}

Sources: mem0-ts/src/oss/src/utils/bm25.ts:1-20

Entity extraction heuristics implemented in extractEntities() parse text into four distinct categories in order of precedence: PROPER (capitalized multi-word sequences), IDENTIFIER (dotted technical paths like person.properties.email), QUOTED (explicitly quoted strings), and TOPIC (noun phrase compounds). Extracted entities are filtered against generic stop lists (GENERIC_HEADS, NON_SPECIFIC_ADJ) and deduplicated. Furthermore, payloadIsExpired() validates memory expiration dates against UTC time, ensuring expired records are omitted from search results unless showExpired is explicitly enabled.

Sources: mem0-ts/src/oss/src/utils/entity_extraction.ts:725-818, mem0-ts/src/oss/src/utils/expiration.ts:39-52

Was this page helpful?