Skip to main content
doc0blade47/mem0documentation home
Sign in

TypeScript Agent Core

Last updated Oct 11, 2026
Relevant source files

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

Overview

The TypeScript Agent Core provides foundational infrastructure and utilities for integrating Mem0 long-term memory into developer coding assistants and agent runtimes. It standardizes state management, prompt generation, scoping, and data formatting across host environments.

Sources: integrations/agent-plugin-core/typescript/src/lifecycle.ts:86-121, integrations/agent-plugin-core/typescript/src/formatting.ts:1-54, integrations/agent-plugin-core/typescript/src/scoping.ts:1-50

Lifecycle hook execution

MemoryLifecycle Class and Session Management

The MemoryLifecycle class implements a shared lifecycle policy where host adapters translate native events into standard memory operations. It manages internal state tracking through a private #seenMemoryIds set and an #options configuration object initialized via MemoryLifecycleOptions.

class MemoryLifecycle {
  readonly #seenMemoryIds = new Set<string>();
  readonly #options: MemoryLifecycleOptions;
 
  constructor(options: MemoryLifecycleOptions = {}) {
    this.#options = options;
  }
 
  beginSession(): void {
    this.#seenMemoryIds.clear();
  }
...

Sources: integrations/agent-plugin-core/typescript/src/lifecycle.ts:86-98

The beginSession() method clears the #seenMemoryIds collection to reset duplicate suppression for a new conversation turn or session. prepareConversation() and prepareUserText() process raw messages and user inputs by extracting text blocks and sanitizing sensitive tokens.

Option KeyTypeDefaultPurpose
recallHeadingstringRECALL_HEADINGCustom heading injected above retrieved memories
maxContextCharsnumber4_000 (DEFAULT_MAX_CONTEXT_CHARS)Maximum character budget for injected memory context
recallTimeoutMsnumber2_000Timeout threshold for asynchronous memory search operations

Sources: integrations/agent-plugin-core/typescript/src/lifecycle.ts:5-6, integrations/agent-plugin-core/typescript/src/lifecycle.ts:80-84, integrations/agent-plugin-core/typescript/src/lifecycle.ts:99-121

Note

The recall method delegates directly to buildRecallContext, passing along the instance's configured heading, character limits, seen memory identifiers, and timeout parameters.

Sources: integrations/agent-plugin-core/typescript/src/lifecycle.ts:109-120

Context Retrieval and Secret Redundancy

The buildRecallContext function orchestrates asynchronous memory retrieval, timeout enforcement, duplicate filtering, and character budgeting. If enabled is false or the bounded query evaluates to empty, it returns an empty string immediately.

export async function buildRecallContext(
  prompt: string,
  enabled: boolean,
  search: (query: string) => Promise<{ results?: unknown[] }>,
  options: RecallOptions = {},
): Promise<string> {
  if (!enabled) return "";
  const query = boundedText(prompt, MAX_RECALL_QUERY_CHARS);
  if (!query) return "";
...

Sources: integrations/agent-plugin-core/typescript/src/lifecycle.ts:129-138

Search execution is wrapped in a Promise.race call against a timeout promise defaulting to 2,000 milliseconds. Retrieved results are filtered against seenIds to omit previously injected memories, and formatted entries are accumulated until maxChars (DEFAULT_MAX_CONTEXT_CHARS) is reached.

const SECRET_PATTERNS: Array<[RegExp, string]> = [
  [/(authorization\s*[:=]\s*(?:bearer|token)\s+)[^\s"']+/gi, "$1[REDACTED]"],
  [
    /((?:api[_-]?key|secret[_-]?access[_-]?key|session[_-]?token)\s*[:=]\s*)[^\s"']+/gi,
    "$1[REDACTED]",
  ],
  [
    /((?:access[_-]?token|refresh[_-]?token|password|credential)\s*[:=]\s*)[^\s&"']+/gi,
    "$1[REDACTED]",
  ],
  [/\b(?:sk|m0|mem0_sk|psk)-[A-Za-z0-9_-]{12,}\b/g, "[REDACTED]"],
  [/\b(?:ASIA|AKIA)[A-Z0-9]{12,}\b/g, "[REDACTED]"],
  [/\b(?:ghp_|github_pat_|xox[baprs]-)[A-Za-z0-9_-]{12,}\b/g, "[REDACTED]"],
  [/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g, "[REDACTED]"],
];

Sources: integrations/agent-plugin-core/typescript/src/lifecycle.ts:8-22

Warning

redactSecrets applies these regular expression patterns to all conversation extracts, user text inputs, and memory compaction outputs to prevent accidental leakage of authorization headers, API keys, private keys, and session tokens into model prompts.

Sources: integrations/agent-plugin-core/typescript/src/lifecycle.ts:24-31, integrations/agent-plugin-core/typescript/src/lifecycle.ts:67-67, integrations/agent-plugin-core/typescript/src/lifecycle.ts:105-107, integrations/agent-plugin-core/typescript/src/lifecycle.ts:160-162

Session scoping resolution

Scope Resolution and Normalization

Memory isolation across execution contexts is governed by the Scope type, supporting "project", "session", and "global" values. The normalizeScope utility enforces this constraint by validating incoming unknown inputs and defaulting unrecognised values to "project".

export type Scope = "project" | "session" | "global";
 
export function normalizeScope(value: unknown): Scope {
  return value === "session" || value === "global" ? value : "project";
}

Sources: integrations/agent-plugin-core/typescript/src/scoping.ts:1-11

When resolving tool execution scopes via resolveToolScope, if a requested scope is absent, the function falls back to the configured default scope.

Caution

If a user requests "global" scope when the configured scope is not "global", resolveToolScope throws an error demanding that the global scope be selected explicitly in plugin settings or via the /mem0-scope command first.

export function resolveToolScope(requested: Scope | undefined, configured: Scope): Scope {
  const scope = requested ?? configured;
  if (scope === "global" && configured !== "global") {
    throw new Error("Select global scope in the plugin settings or /mem0-scope command first.");
  }
  return scope;
}

Sources: integrations/agent-plugin-core/typescript/src/scoping.ts:13-19

Context Validation and Filter Mapping

The ScopeContext interface requires specific identification properties depending on the active hierarchy level. Validation rules inspect context properties to ensure required identifiers are present and non-empty.

ScopeRequired Context KeysValidation Behavior
"global"userIdValidates userId is present, trimmed, and not wildcarded (*)
"project"userId, appIdValidates both userId and appId
"session"userId, appId, runIdValidates userId, appId, and runId

Sources: integrations/agent-plugin-core/typescript/src/scoping.ts:3-7, integrations/agent-plugin-core/typescript/src/scoping.ts:21-30

Warning

validateContext throws an Error prefixed with "Invalid memory scope" if any evaluated key is empty, undefined, whitespace-only, or composed entirely of asterisks (*+).

function validateContext(scope: Scope, context: ScopeContext): void {
  const keys: (keyof ScopeContext)[] = ["userId"];
  if (scope !== "global") keys.push("appId");
  if (scope === "session") keys.push("runId");
  for (const key of keys) {
    if (!context[key]?.trim() || /^\*+$/.test(context[key].trim())) {
      throw new Error(`Invalid memory scope ${key}`);
    }
  }
}

Sources: integrations/agent-plugin-core/typescript/src/scoping.ts:21-30

Search filters and add parameters translate validated scopes into concrete key-value dictionaries. The scopeSearchFilters function maps scopes to database-query filters, whereas scopeAddParams formats payload parameters for memory persistence operations.

export function scopeSearchFilters(scope: Scope, context: ScopeContext): Record<string, string> {
  validateContext(scope, context);
  if (scope === "session") {
    return { user_id: context.userId, app_id: context.appId, run_id: context.runId };
  }
  return scope === "global"
    ? { user_id: context.userId }
    : { user_id: context.userId, app_id: context.appId };
}

Sources: integrations/agent-plugin-core/typescript/src/scoping.ts:32-40

export function scopeAddParams(scope: Scope, context: ScopeContext): Record<string, string> {
  validateContext(scope, context);
  if (scope === "session") {
    return { userId: context.userId, appId: context.appId, runId: context.runId };
  }
  return scope === "global"
    ? { userId: context.userId }
    : { userId: context.userId, appId: context.appId };
}

Sources: integrations/agent-plugin-core/typescript/src/scoping.ts:42-50

Identity detection and entity parameters

Entity Parameters Structure and Normalization

The EntityParams interface defines the core attribution properties used across memory search and persistence operations. It supports three optional identifiers: userId, agentId, and runId.

export interface EntityParams {
  userId?: string;
  agentId?: string;
  runId?: string;
}

Sources: integrations/agent-plugin-core/typescript/src/identity.ts:1-5

An internal helper function clean trims string inputs, translating empty or whitespace-only strings into undefined.

const clean = (value: string | undefined): string | undefined => value?.trim() || undefined;

Sources: integrations/agent-plugin-core/typescript/src/identity.ts:7-7

Filter Mapping and Parameter Construction

Entity parameters are translated into database search filters and memory addition payload parameters via dedicated helper functions. Both entitySearchFilters and entityAddParams accept an EntityParams object and a fallback defaultUserId.

export function entitySearchFilters(
  params: EntityParams,
  defaultUserId: string,
): Record<string, string> {
  const filters: Record<string, string> = { user_id: clean(params.userId) ?? defaultUserId };
  const agentId = clean(params.agentId);
  const runId = clean(params.runId);
  if (agentId) filters.agent_id = agentId;
  if (runId) filters.run_id = runId;
  return filters;
}

Sources: integrations/agent-plugin-core/typescript/src/identity.ts:9-19

export function entityAddParams(params: EntityParams, defaultUserId: string): Record<string, string> {
  const values: Record<string, string> = { userId: clean(params.userId) ?? defaultUserId };
  const agentId = clean(params.agentId);
  const runId = clean(params.runId);
  if (agentId) values.agentId = agentId;
  if (runId) values.runId = runId;
  return values;
}

Sources: integrations/agent-plugin-core/typescript/src/identity.ts:21-28

FunctionOutput Key FormatFallback BehaviorOptional Keys Included
entitySearchFiltersuser_id, agent_id, run_idclean(params.userId) ?? defaultUserIdagent_id, run_id
entityAddParamsuserId, agentId, runIdclean(params.userId) ?? defaultUserIdagentId, runId

Sources: integrations/agent-plugin-core/typescript/src/identity.ts:9-28

Remote Git URL Parsing

The parseProjectFromRemote function extracts project identifiers from Git remote URL strings using a regular expression that matches organization and repository segments while stripping optional .git suffixes and trailing slashes.

export function parseProjectFromRemote(remote: string): string | null {
  const match = remote.trim().match(/[:/]([^/:]+)\/([^/:]+?)(?:\.git)?\/?$/);
  return match ? `${match[1]}-${match[2]}` : null;
}

Sources: integrations/agent-plugin-core/typescript/src/identity.ts:30-33

Note

parseProjectFromRemote expects standard SSH or HTTPS remote strings (such as git@github.com:owner/repo.git or https://github.com/owner/repo), returning a hyphenated ${owner}-${repo} string or null if the pattern fails to match. Sources: integrations/agent-plugin-core/typescript/src/identity.ts:30-33

Prompt synthesis and guidance constants

Repository and User-Scoped Prompt Constants

Standardizing prompt directives, search timing triggers, and query descriptions enables consistent LLM tool selection across repository-scoped and general user contexts. The prompts.ts module exports static string constants that define search triggers, tool descriptions, query descriptions, and injection headers.

The prompt constants are partitioned into repository-scoped variants and general user-scoped variants. The SEARCH_WHEN trigger specifies execution timing for search actions.

export const SEARCH_WHEN =
  "before repeating investigation or when earlier decisions, fixes, commands, or results may help";

Sources: integrations/agent-plugin-core/typescript/src/prompts.ts:1-2

Repository-scoped constants bind tool behavior to the current repository scope, whereas user-scoped constants omit repository restrictions.

Constant NameValueScopeSources
SEARCH_WHEN"before repeating investigation or when earlier decisions, fixes, commands, or results may help"Shared Triggerintegrations/agent-plugin-core/typescript/src/prompts.ts:1-2
SEARCH_TOOL_DESCRIPTION"Search memories from earlier work in this repository. Use it " + SEARCH_WHEN + "."Repositoryintegrations/agent-plugin-core/typescript/src/prompts.ts:4-4
SEARCH_QUERY_DESCRIPTION"A direct question about earlier work in this repository."Repositoryintegrations/agent-plugin-core/typescript/src/prompts.ts:5-5
RECALL_HEADING"Mem0 found these relevant memories from earlier work in this repository:"Repositoryintegrations/agent-plugin-core/typescript/src/prompts.ts:6-6
USER_SEARCH_TOOL_DESCRIPTION"Search memories from earlier work. Use it " + SEARCH_WHEN + "."General Userintegrations/agent-plugin-core/typescript/src/prompts.ts:8-8
USER_SEARCH_QUERY_DESCRIPTION"A direct question about earlier work."General Userintegrations/agent-plugin-core/typescript/src/prompts.ts:9-9
USER_RECALL_HEADING"Mem0 found these relevant memories from earlier work:"General Userintegrations/agent-plugin-core/typescript/src/prompts.ts:10-10

Sources: integrations/agent-plugin-core/typescript/src/prompts.ts:1-10

Memory formatting interfaces

Memory Data Structures and Output Formatting

The Typescript Core defines data structures and formatting utilities to transform retrieved records into compact injection formats for agent contexts. The core data contract is represented by the MemoryLike interface, which models individual stored memory records with identifiers, text payloads, categorical labels, and creation timestamps.

export interface MemoryLike {
  id: string;
  memory?: string;
  categories?: string[];
  createdAt?: Date | string;
}

Sources: integrations/agent-plugin-core/typescript/src/formatting.ts:1-6

To prevent context bloat during model injection and CLI reporting, output limits enforce boundaries on serialized memory text. Maximum output constraints restrict total lines, character counts, and byte sizes.

export const MAX_OUTPUT_LINES = 200;
export const MAX_OUTPUT_CHARS = 50_000;
export const MAX_OUTPUT_BYTES = MAX_OUTPUT_CHARS;

Sources: integrations/agent-plugin-core/typescript/src/formatting.ts:8-10

Constant / InterfaceType / ValuePurposeSources
MemoryLikeInterfaceModels memory records (id, memory, categories, createdAt)integrations/agent-plugin-core/typescript/src/formatting.ts:1-6
MAX_OUTPUT_LINES200Limits total rendered lines for memory outputintegrations/agent-plugin-core/typescript/src/formatting.ts:8-8
MAX_OUTPUT_CHARS50_000Limits total character length for memory outputintegrations/agent-plugin-core/typescript/src/formatting.ts:9-9
MAX_OUTPUT_BYTESMAX_OUTPUT_CHARSLimits total byte size for memory outputintegrations/agent-plugin-core/typescript/src/formatting.ts:10-10

Sources: integrations/agent-plugin-core/typescript/src/formatting.ts:1-10

Transformation and Truncation Functions

Retrieved records are formatted into readable strings using utility functions that calculate relative age, apply category badges, and structure lists. The formatAge function computes time intervals in minutes, hours, or days from a timestamp.

export function formatAge(date: Date | string): string {
  const minutes = Math.floor((Date.now() - new Date(date).getTime()) / 60_000);
  if (minutes < 60) return `${minutes}m ago`;
  const hours = Math.floor(minutes / 60);
  return hours < 24 ? `${hours}h ago` : `${Math.floor(hours / 24)}d ago`;
}

Sources: integrations/agent-plugin-core/typescript/src/formatting.ts:12-17

The formatMemoryCompact function builds a single-line representation containing the primary category, memory text, age suffix, and memory identifier tag.

export function formatMemoryCompact(memory: MemoryLike): string {
  const category = memory.categories?.[0] ?? "uncategorized";
  const age = memory.createdAt ? ` (${formatAge(memory.createdAt)})` : "";
  return `[${category}] ${memory.memory ?? "(empty)"}${age} [mem0:${memory.id}]`;
}

Sources: integrations/agent-plugin-core/typescript/src/formatting.ts:19-23

Note

When multiple memory records are returned, formatMemoryList maps over the array to generate a numbered list, falling back to a default string if no records exist. Sources: integrations/agent-plugin-core/typescript/src/formatting.ts:25-29

The execution walkthrough begins when the apply function is invoked in the DeepSeek plugin. It delegates to stateFor to retrieve or initialize the session state, which invokes createMemoryLifecycle to instantiate a new MemoryLifecycle instance for managing conversation preparation and memory recall.

Sources: integrations/deepseek-plugin/src/index.ts:96-121, integrations/agent-plugin-core/typescript/src/lifecycle.ts:87-127

Was this page helpful?