# How TencentDB Agent Memory Enables AI Agents to Share Context Across Sessions

> Discover how TencentDB Agent Memory uses hierarchical storage and HTTP gateway to let stateless AI agents share conversational context across sessions with team user and agent IDs.

- Repository: [Tencent Cloud/TencentDB-Agent-Memory](https://github.com/TencentCloud/TencentDB-Agent-Memory)
- Tags: how-to-guide
- Published: 2026-09-01

---

**TencentDB Agent Memory implements a centralized HTTP gateway with hierarchical storage layers (L0–L3) and deterministic turn sequencing, allowing stateless AI agents to persist and retrieve shared conversational context using standardized team, user, and agent identifiers.**

The TencentCloud/TencentDB-Agent-Memory repository solves the stateless nature of traditional AI agents by introducing a service-oriented architecture that decouples memory storage from agent runtime. By treating memory as a shared service rather than local state, multiple specialized agents can collaboratively build upon previous conversations across distinct sessions and execution contexts.

## The Layered Architecture Behind Cross-Session Memory

The system separates concerns into three primary services that collectively enable **cross-session context sharing** without requiring client-side state management.

### Memory Hub: The Centralized Gateway

The **Memory Hub** acts as the sole entry point for all memory operations. Implemented in [`MemoryProxy/src/tdai/client.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryProxy/src/tdai/client.ts), this HTTP gateway validates access control lists (ACLs), injects turn-sequence metadata, and routes requests to the appropriate backend services. Every request carries a `x-tdai-user-key` header that the gateway transforms into `team_id`, `user_id`, and `agent_id` parameters, ensuring that memory operations are scoped to the correct organizational boundaries while remaining accessible to authorized agents.

### Memory Core: Hierarchical Storage (L0–L3)

According to [`MemoryCore/v3-api-memorycore-doc.md`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryCore/v3-api-memorycore-doc.md), the system organizes persistent storage into four distinct levels:

- **L0 (Raw Conversations)**: Complete message logs chunked to respect 8KB limits
- **L1 (Token Embeddings)**: Vector representations enabling semantic search across sessions
- **L2 (Scenario Files)**: Hierarchical file structures containing tool outputs and code snippets
- **L3 (Core Knowledge)**: Global knowledge entries shared across all sessions

This分层 design allows agents to choose the appropriate granularity when retrieving context, from exact message logs to high-level semantic concepts.

### Memory Knowledge: Shared Semantic Search

As documented in [`MemoryKnowledge/v3-api-memoryknowledge-doc.md`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryKnowledge/v3-api-memoryknowledge-doc.md), the knowledge base provides searchable indices that any authorized agent can query. Unlike isolated agent memory, this layer enables **semantic retrieval** of information stored by different agents within the same team-user scope.

## How Context Propagation Works Across Agent Boundaries

Context sharing relies on a strict identity propagation mechanism defined in [`MemoryProxy/src/tdai/client.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryProxy/src/tdai/client.ts). When an agent initializes the `TdaiClient`, it provides a context object containing `teamId`, `userId`, and `agentId`. These identifiers accompany every request through the `postForCtx` method, which appends `session_id` and `task_id` headers to track logical groupings.

The `AclCheckParams` interface enforces security at the gateway level:

```typescript
// source: MemoryProxy/src/tdai/client.ts (lines 57-78)
export interface AclCheckParams {
  user_key: string;
  asset_id: string;
  action: string;
  agent_id?: string;
}

```

Every read or write operation validates these parameters before accessing storage, ensuring agents can only interact with memory entries within their authorized scope.

## Writing and Retrieving Shared Memory

The `TdaiClient` class exposes methods that enable bidirectional context flow between agents, regardless of which specific agent instance created the original data.

### Persisting L0 Raw Conversations with `addConversation`

When an agent completes a user interaction, it calls `addConversation` to persist the raw message history. The client automatically chunks payloads exceeding 8KB and posts them to `/v3/conversation/add` with the full identity context:

```typescript
// source: MemoryProxy/src/tdai/client.ts (lines 91-124)
await this.postForCtx(
    "/v3/conversation/add",
    { teamId: identity.teamId, userId: identity.userId, agentId: identity.agentId },
    { /* messages batch */ },
    identity.sessionId,
    identity.taskId,
    { includeSession: true, includeTask: true },
);

```

Because the request includes the **team-user-agent triple**, the conversation becomes visible to any other agent querying the same identifiers, effectively breaking session isolation.

### Querying L1 Semantic Embeddings with `searchL1`

Agents retrieve semantic context through the `searchL1` method, which calls `/v3/atomic/search` with the caller's credentials while preserving the original `session_id` and `task_id` from the source conversation:

```typescript
// source: MemoryProxy/src/tdai/client.ts (lines 26-34)
const data = await this.postForCtx(
    "/v3/atomic/search",
    ctx,
    { /* query params */, session_id: sessionId, task_id: taskId },
);

```

This design allows a "documentation-agent" to store embeddings during one session, while a "coding-agent" retrieves them hours later in a completely different session, creating the illusion of continuous memory.

### Accessing L2 Scenarios and L3 Knowledge with `listL2ForCtx`

The `listL2ForCtx` method retrieves hierarchical scenario files stored under the same organizational scope. Agents supply their current `session_id` and `task_id` to merge historical artifacts with active context:

```typescript
// source: MemoryProxy/src/tdai/client.ts (lines 84-98)
await this.postForCtx("/v3/scenario/ls", ctx, { 
  team_id, 
  agent_id, 
  path_prefix: "" 
});

```

## Turn Sequencing and Trace Alignment

Multi-agent collaboration requires deterministic grouping of related operations. The system calculates turn sequence numbers in [`MemoryProxy/src/turnSeq.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryProxy/src/turnSeq.ts) using the `countHumanTurns` function:

```typescript
// source: MemoryProxy/src/turnSeq.ts (lines 44-55)
export function countHumanTurns(messages, protocol) {
    // Counts human-user messages to generate deterministic sequence IDs
}

```

The gateway uses this count to assign identical `turnSeq` values to all requests belonging to the same logical human turn. This enables **Langfuse-style trace stitching**, where different agents participating in the same conversation turn appear grouped in telemetry dashboards, even when they execute asynchronously across separate microservices.

## Complete Implementation Example

The following example demonstrates how Agent A (workbuddy) stores context that Agent B (codeassistant) retrieves in a subsequent session:

```typescript
import { TdaiClient } from "./MemoryProxy/src/tdai/client.js";

const cfg = {
  enabled: true,
  endpoint: "https://memory.example.com",
  writeL0: true,
  recallL1: true,
  injectL2L3: true,
  l1Limit: 5,
};

const client = new TdaiClient(cfg);

// Agent A writes the latest user turn
await client.addConversation(
  { 
    teamId: "team123", 
    userId: "u42", 
    agentId: "workbuddy", 
    sessionId: "s99", 
    taskId: "t5" 
  },
  [{ role: "user", content: "How do I backup my DB?" }]
);

// Agent B retrieves the same context in a different session
const pastEmbeddings = await client.searchL1(
  { 
    teamId: "team123", 
    userId: "u42", 
    agentId: "codeassistant", 
    sessionId: "s101", 
    taskId: "t7" 
  },
  "backup"
);

// Agent B lists scenario files generated earlier
const files = await client.listL2ForCtx(
  { teamId: "team123", userId: "u42", agentId: "codeassistant" }
);

```

## Summary

- **TencentDB Agent Memory** uses a centralized hub-and-spoke architecture to decouple memory from agent runtime, enabling stateless AI agents to share context.
- **Hierarchical storage layers (L0–L3)** provide granular access to raw conversations, semantic embeddings, scenario files, and global knowledge.
- **Identity propagation** via `team_id`, `user_id`, and `agent_id` ensures memory entries are accessible across sessions while maintaining strict ACL boundaries.
- **Deterministic turn sequencing** aligns multi-agent operations into logical conversation turns for coherent telemetry and debugging.
- The `TdaiClient` TypeScript implementation in [`MemoryProxy/src/tdai/client.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryProxy/src/tdai/client.ts) provides the primary API for cross-session memory operations.

## Frequently Asked Questions

### What are the L0–L3 storage layers in TencentDB Agent Memory?

The L0 layer stores raw conversation logs chunked to 8KB segments. L1 contains token-level embeddings for semantic search. L2 holds hierarchical scenario files and tool outputs, while L3 maintains global core knowledge accessible across all sessions. According to [`MemoryCore/v3-api-memorycore-doc.md`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryCore/v3-api-memorycore-doc.md), this architecture allows agents to retrieve context at the appropriate level of abstraction.

### How does the turn sequence number enable multi-agent collaboration?

The gateway computes a deterministic `turnSeq` using `countHumanTurns` from [`MemoryProxy/src/turnSeq.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryProxy/src/turnSeq.ts) based on the number of human messages in the conversation history. All operations within the same logical turn receive identical sequence numbers, allowing distributed agents to be grouped together in tracing systems like Langfuse, even when they execute across different processes or time windows.

### Can agents from different teams share memory contexts?

No, the ACL system strictly isolates memory by `team_id`. The `AclCheckParams` interface in [`MemoryProxy/src/tdai/client.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryProxy/src/tdai/client.ts) validates every request against the user key and team membership. While agents with different `agent_id` values can share memory within the same team and user scope, cross-team access is prohibited at the gateway level.

### What is the maximum payload size for conversation writes?

The `addConversation` method in `TdaiClient` automatically chunks messages to respect an 8KB limit per batch. When persisting L0 raw conversations, the client splits large message arrays into multiple `POST /v3/conversation/add` requests to ensure reliable transmission through the Memory Hub gateway.