---
title: "TypeScript Agent Core"
description: "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 managem..."
last_updated: "2026-10-11T17:37:10.212608+00:00"
canonical_url: "https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/technical/agent-plugins/typescript-agent-core"
---

<details>
<summary>Relevant source files</summary>

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

- [integrations/opencode-plugin/opencode-mem0.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/opencode-plugin/opencode-mem0.ts)
- [integrations/agent-plugin-core/typescript/src/lifecycle.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/lifecycle.ts)
- [mem0-ts/src/oss/src/memory/index.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/oss/src/memory/index.ts)
- [integrations/agent-plugin-core/python/hook_runner.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/python/hook_runner.py)
- [integrations/kimi-plugin/core/hook_runner.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/kimi-plugin/core/hook_runner.py)
- [integrations/antigravity-plugin/core/hook_runner.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/antigravity-plugin/core/hook_runner.py)
- [integrations/agent-plugin-core/python/memory_core.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/python/memory_core.py)
- [integrations/cursor-plugin/core/memory_core.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/cursor-plugin/core/memory_core.py)
- [integrations/mem0-agent-plugin/core/memory_core.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/mem0-agent-plugin/core/memory_core.py)
- [integrations/openclaw/index.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/openclaw/index.ts)
- [integrations/antigravity-plugin/core/memory_core.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/antigravity-plugin/core/memory_core.py)
- [integrations/deepseek-plugin/src/index.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/deepseek-plugin/src/index.ts)
- [integrations/kimi-plugin/core/memory_core.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/kimi-plugin/core/memory_core.py)
- [integrations/codex-plugin/core/memory_core.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/codex-plugin/core/memory_core.py)
- [integrations/claude-code-plugin/core/memory_core.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/claude-code-plugin/core/memory_core.py)
- [mem0-ts/src/community/src/integrations/langchain/mem0.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/community/src/integrations/langchain/mem0.ts)
- [integrations/openclaw/recall.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/openclaw/recall.ts)
- [integrations/hermes-plugin-mem0/__init__.py](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/hermes-plugin-mem0/__init__.py)
- [integrations/vercel-ai-sdk/src/mem0-generic-language-model.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/vercel-ai-sdk/src/mem0-generic-language-model.ts)
- [integrations/pi-agent-plugin/src/memory/tools.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/pi-agent-plugin/src/memory/tools.ts)
- [integrations/openclaw/isolation.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/openclaw/isolation.ts)
- [mem0-ts/src/oss/src/prompts/index.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/oss/src/prompts/index.ts)
- [mem0-ts/src/oss/src/llms/langchain.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/mem0-ts/src/oss/src/llms/langchain.ts)
- [integrations/agent-plugin-core/typescript/src/formatting.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/formatting.ts)
- [integrations/agent-plugin-core/typescript/src/identity.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/identity.ts)
- [integrations/agent-plugin-core/typescript/src/prompts.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/prompts.ts)
- [integrations/agent-plugin-core/typescript/src/scoping.ts](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/scoping.ts)
</details>

## 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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/lifecycle.ts#L86-L121), [integrations/agent-plugin-core/typescript/src/formatting.ts:1-54](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/formatting.ts#L1-L54), [integrations/agent-plugin-core/typescript/src/scoping.ts:1-50](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/scoping.ts#L1-L50)

## 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`.

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/lifecycle.ts#L86-L98)

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 Key | Type | Default | Purpose |
| :--- | :--- | :--- | :--- |
| `recallHeading` | `string` | `RECALL_HEADING` | Custom heading injected above retrieved memories |
| `maxContextChars` | `number` | `4_000` (`DEFAULT_MAX_CONTEXT_CHARS`) | Maximum character budget for injected memory context |
| `recallTimeoutMs` | `number` | `2_000` | Timeout threshold for asynchronous memory search operations |

Sources: [integrations/agent-plugin-core/typescript/src/lifecycle.ts:5-6](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/lifecycle.ts#L5-L6), [integrations/agent-plugin-core/typescript/src/lifecycle.ts:80-84](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/lifecycle.ts#L80-L84), [integrations/agent-plugin-core/typescript/src/lifecycle.ts:99-121](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/lifecycle.ts#L99-L121)

> [!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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/lifecycle.ts#L109-L120)

### 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.

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/lifecycle.ts#L129-L138)

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.

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/lifecycle.ts#L8-L22)

> [!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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/lifecycle.ts#L24-L31), [integrations/agent-plugin-core/typescript/src/lifecycle.ts:67-67](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/lifecycle.ts#L67-L67), [integrations/agent-plugin-core/typescript/src/lifecycle.ts:105-107](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/lifecycle.ts#L105-L107), [integrations/agent-plugin-core/typescript/src/lifecycle.ts:160-162](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/lifecycle.ts#L160-L162)

## 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"`.

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/scoping.ts#L1-L11)

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.

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/scoping.ts#L13-L19)

### 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.

| Scope | Required Context Keys | Validation Behavior |
| :--- | :--- | :--- |
| `"global"` | `userId` | Validates `userId` is present, trimmed, and not wildcarded (`*`) |
| `"project"` | `userId`, `appId` | Validates both `userId` and `appId` |
| `"session"` | `userId`, `appId`, `runId` | Validates `userId`, `appId`, and `runId` |

Sources: [integrations/agent-plugin-core/typescript/src/scoping.ts:3-7](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/scoping.ts#L3-L7), [integrations/agent-plugin-core/typescript/src/scoping.ts:21-30](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/scoping.ts#L21-L30)

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

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/scoping.ts#L21-L30)

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.

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/scoping.ts#L32-L40)

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/scoping.ts#L42-L50)

## 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`.

```typescript
export interface EntityParams {
  userId?: string;
  agentId?: string;
  runId?: string;
}
```
Sources: [integrations/agent-plugin-core/typescript/src/identity.ts:1-5](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/identity.ts#L1-L5)

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

```typescript
const clean = (value: string | undefined): string | undefined => value?.trim() || undefined;
```
Sources: [integrations/agent-plugin-core/typescript/src/identity.ts:7-7](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/identity.ts#L7-L7)

### 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`.

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/identity.ts#L9-L19)

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/identity.ts#L21-L28)

| Function | Output Key Format | Fallback Behavior | Optional Keys Included |
| :--- | :--- | :--- | :--- |
| `entitySearchFilters` | `user_id`, `agent_id`, `run_id` | `clean(params.userId) ?? defaultUserId` | `agent_id`, `run_id` |
| `entityAddParams` | `userId`, `agentId`, `runId` | `clean(params.userId) ?? defaultUserId` | `agentId`, `runId` |

Sources: [integrations/agent-plugin-core/typescript/src/identity.ts:9-28](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/identity.ts#L9-L28)

### 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.

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/identity.ts#L30-L33)

> [!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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/identity.ts#L30-L33)

## 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.

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/prompts.ts#L1-L2)

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

| Constant Name | Value | Scope | Sources |
| :--- | :--- | :--- | :--- |
| `SEARCH_WHEN` | `"before repeating investigation or when earlier decisions, fixes, commands, or results may help"` | Shared Trigger | [integrations/agent-plugin-core/typescript/src/prompts.ts:1-2](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/prompts.ts#L1-L2) |
| `SEARCH_TOOL_DESCRIPTION` | `"Search memories from earlier work in this repository. Use it " + SEARCH_WHEN + "."` | Repository | [integrations/agent-plugin-core/typescript/src/prompts.ts:4-4](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/prompts.ts#L4-L4) |
| `SEARCH_QUERY_DESCRIPTION` | `"A direct question about earlier work in this repository."` | Repository | [integrations/agent-plugin-core/typescript/src/prompts.ts:5-5](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/prompts.ts#L5-L5) |
| `RECALL_HEADING` | `"Mem0 found these relevant memories from earlier work in this repository:"` | Repository | [integrations/agent-plugin-core/typescript/src/prompts.ts:6-6](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/prompts.ts#L6-L6) |
| `USER_SEARCH_TOOL_DESCRIPTION` | `"Search memories from earlier work. Use it " + SEARCH_WHEN + "."` | General User | [integrations/agent-plugin-core/typescript/src/prompts.ts:8-8](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/prompts.ts#L8-L8) |
| `USER_SEARCH_QUERY_DESCRIPTION` | `"A direct question about earlier work."` | General User | [integrations/agent-plugin-core/typescript/src/prompts.ts:9-9](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/prompts.ts#L9-L9) |
| `USER_RECALL_HEADING` | `"Mem0 found these relevant memories from earlier work:"` | General User | [integrations/agent-plugin-core/typescript/src/prompts.ts:10-10](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/prompts.ts#L10-L10) |

Sources: [integrations/agent-plugin-core/typescript/src/prompts.ts:1-10](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/prompts.ts#L1-L10)

## Memory formatting interfaces

### Memory Data Structures and Output Formatting

The [Typescript Core](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/technical/typescript-core/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.

```typescript
export interface MemoryLike {
  id: string;
  memory?: string;
  categories?: string[];
  createdAt?: Date | string;
}
```
Sources: [integrations/agent-plugin-core/typescript/src/formatting.ts:1-6](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/formatting.ts#L1-L6)

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.

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/formatting.ts#L8-L10)

| Constant / Interface | Type / Value | Purpose | Sources |
| :--- | :--- | :--- | :--- |
| `MemoryLike` | Interface | Models memory records (`id`, `memory`, `categories`, `createdAt`) | [integrations/agent-plugin-core/typescript/src/formatting.ts:1-6](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/formatting.ts#L1-L6) |
| `MAX_OUTPUT_LINES` | `200` | Limits total rendered lines for memory output | [integrations/agent-plugin-core/typescript/src/formatting.ts:8-8](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/formatting.ts#L8-L8) |
| `MAX_OUTPUT_CHARS` | `50_000` | Limits total character length for memory output | [integrations/agent-plugin-core/typescript/src/formatting.ts:9-9](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/formatting.ts#L9-L9) |
| `MAX_OUTPUT_BYTES` | `MAX_OUTPUT_CHARS` | Limits total byte size for memory output | [integrations/agent-plugin-core/typescript/src/formatting.ts:10-10](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/formatting.ts#L10-L10) |

Sources: [integrations/agent-plugin-core/typescript/src/formatting.ts:1-10](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/formatting.ts#L1-L10)

### 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.

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/formatting.ts#L12-L17)

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

```typescript
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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/formatting.ts#L19-L23)

> [!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](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/formatting.ts#L25-L29)

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.

```mermaid
sequenceDiagram
    participant apply as apply()
    participant stateFor as stateFor()
    participant createMemoryLifecycle as createMemoryLifecycle()
    participant MemoryLifecycle as MemoryLifecycle

    apply->>stateFor: Resolve active session state
    stateFor->>createMemoryLifecycle: Initialize lifecycle instance if missing
    createMemoryLifecycle->>MemoryLifecycle: Instantiate MemoryLifecycle class
    MemoryLifecycle-->>apply: Return configured lifecycle policy
```
Sources: [integrations/deepseek-plugin/src/index.ts:96-121](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/deepseek-plugin/src/index.ts#L96-L121), [integrations/agent-plugin-core/typescript/src/lifecycle.ts:87-127](https://github.com/blade47/mem0/blob/b7ad69afda6b6ed030347c66d48a13e4de9dec08/integrations/agent-plugin-core/typescript/src/lifecycle.ts#L87-L127)

## Related

- [Python Agent Core](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/technical/agent-plugins/python-agent-core)
- [OpenCode Integration](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/technical/agent-plugins/opencode-integration)
- [OpenClaw Integration](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/technical/agent-plugins/openclaw-integration)


## Sitemap

See the full [sitemap](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/llms.txt) for all pages in this wiki.
