# How to Refresh the Agent Session Cache Using MemoryProxy

> Refresh agent session cache with MemoryProxy by sending the mem:session-reset command. This action clears cached session state and forces reinitialization for a seamless experience.

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

---

**To refresh the agent session cache using MemoryProxy, send the built-in `mem:session-reset` command in your WorkBuddy request, which triggers the pre-intercept handler in [`workbuddyHandler.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/workbuddyHandler.ts) to clear the cached session state and force a complete session reinitialization.**

The TencentDB-Agent-Memory repository provides the MemoryProxy component to manage per-agent session state in an in-memory store. When you need to force a fresh session context—clearing all cached capabilities and injection blocks—the `mem:session-reset` command provides a direct mechanism to refresh the agent session cache using MemoryProxy's internal handlers.

## How the Session Reset Flow Works

MemoryProxy maintains agent session state in a dedicated in-memory session store (see [`MemoryProxy/src/session/store.js`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryProxy/src/session/store.js)). When a request arrives at the `handleWorkbuddyEndpoint` function in [`MemoryProxy/src/workbuddyHandler.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryProxy/src/workbuddyHandler.ts) (line 998), the system performs a pre-intercept step to check for mem commands before processing the request normally.

The refresh operation follows a strict sequence to ensure complete cache invalidation:

- **Command detection** via `isSessionResetCommand` in [`pre-intercept.js`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/pre-intercept.js)
- **Validation** against allowed commands in `memCommand` configuration
- **Cache eviction** by resetting the session store binding and deleting the binding repository entry
- **Optional archival** of lingering skill buffers via `forceArchive` (around line 1030)
- **Fallback** to the standard session initialization flow

## Detecting and Processing the Reset Command

### Identifying mem:session-reset

When `handleWorkbuddyEndpoint` receives a request, it immediately imports the pre-intercept module to detect control commands:

```typescript
const { isSessionResetCommand } = await import("./mem-command/pre-intercept.js");
if (isSessionResetCommand(body, agentSource)) { … }

```

This check examines the request body for the specific `mem:session-reset` command text, validating it against the agent source before proceeding.

### Clearing the Session Store Cache

Upon validation, the handler clears the cached `WorkbuddySessionState` by resetting the store binding for the current `compositeKey` (derived from the `session-id` header or a generated key):

```typescript
store.bind(compositeKey, {
  userId: userId || "anonymous",
  agentSource,
  sessionId: sessionKey,
  spaceId,
});
await store.set(compositeKey, {
  status: "uninitialized",
  keyId: sessionKey,
  startedAt: Date.now(),
  attemptCount: 0,
  userId: userId || "anonymous",
  resetEpoch: Date.now(),
  resetFlow: true,
});
const bindingRepo = store.getBindingRepo();
if (bindingRepo) await bindingRepo.deleteBinding(spaceId, sessionKey);

```

This sequence wipes the existing session state, setting `status: "uninitialized"` and `resetFlow: true` to signal that the next request must rebuild the session context from scratch.

### Archiving and Reinitialization

Before completing the reset, the handler optionally triggers `forceArchive` to persist any lingering skill buffers from the Core-Skill client. After archival, the request falls through to the normal session-init flow defined in [`MemoryProxy/src/session/index.js`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryProxy/src/session/index.js), which rebuilds the session context and asset capabilities.

## Implementing Session Refresh in Practice

### Sending a Reset via cURL

To refresh the cache manually, send a request with the `mem:session-reset` command in the message content:

```bash
curl -X POST https://proxy.example.com/workbuddy/<space-id>/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <your‑api‑key>" \
  -H "session-id: my-session-123" \
  -d '{
        "model": "gpt-4o",
        "input": [
          { "type": "message", "role": "user",
            "content": [{ "type": "text", "text": "mem:session‑reset" }]
          }
        ],
        "stream": false
      }'

```

### Programmatic Reset in TypeScript

For automated cache management, implement the reset logic using your HTTP client:

```typescript
import { fetch } from "undici";

async function resetSession(sessionId: string, apiKey: string, spaceId: string) {
  const url = `https://proxy.example.com/workbuddy/${spaceId}/v1/chat/completions`;
  const body = {
    model: "gpt-4o",
    input: [
      {
        type: "message",
        role: "user",
        content: [{ type: "text", text: "mem:session‑reset" }],
      },
    ],
    stream: false,
  };

  const resp = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${apiKey}`,
      "session-id": sessionId,
    },
    body: JSON.stringify(body),
  });

  const json = await resp.json();
  console.log("Reset response:", json);
}

```

### Verifying the Cache Was Cleared

Confirm the refresh succeeded by sending a subsequent request without the reset command. A successful cache clear means the response will **not** contain previously injected `<tdai_injections>` blocks:

```bash
curl -X POST https://proxy.example.com/workbuddy/<space-id>/v1/chat/completions \
  -H "Authorization: Bearer <your‑api‑key>" \
  -H "session-id: my-session-123" \
  -d '{
        "model": "gpt-4o",
        "input": [
          { "type": "message", "role": "user",
            "content": [{ "type": "text", "text": "Hello!" }]
          }
        ],
        "stream": false
      }'

```

If the session was properly refreshed, the response omits any cached injection context, indicating the session state machine reinitialized successfully.

## Key Source Files in the Reset Architecture

Understanding the complete refresh flow requires familiarity with these specific files in the TencentDB-Agent-Memory repository:

- **[`MemoryProxy/src/workbuddyHandler.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryProxy/src/workbuddyHandler.ts)** – Contains the `handleWorkbuddyEndpoint` entry point (line 998) and the pre-intercept logic that orchestrates the cache reset.
- **[`MemoryProxy/src/mem-command/pre-intercept.js`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryProxy/src/mem-command/pre-intercept.js)** – Implements `isSessionResetCommand` to detect reset commands before request processing.
- **[`MemoryProxy/src/mem-command/index.js`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryProxy/src/mem-command/index.js)** – Parses and validates command text against the `memCommand` configuration.
- **[`MemoryProxy/src/session/store.js`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryProxy/src/session/store.js)** – Provides the in-memory session store with `bind`, `set`, and `getBindingRepo` methods used to clear cached state.
- **[`MemoryProxy/src/session/index.js`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryProxy/src/session/index.js)** – Defines `handleSessionInit` and related helpers that rebuild session context after a cache reset.

## Summary

- **Use `mem:session-reset`** to trigger the built-in cache refresh mechanism in MemoryProxy.
- **The reset flow** executes in `handleWorkbuddyEndpoint` via pre-intercept detection, validates against `memCommand` config, and clears the `WorkbuddySessionState` from the in-memory store.
- **Cache eviction** involves calling `store.set` with `status: "uninitialized"` and `resetFlow: true`, plus `bindingRepo.deleteBinding` to remove the session mapping.
- **Verification** requires checking that subsequent responses lack cached `<tdai_injections>` blocks, confirming the session reinitialized cleanly.
- **Source files** in `MemoryProxy/src/` define the complete architecture for session management and cache invalidation.

## Frequently Asked Questions

### What happens to active skills when I reset the session cache?

The reset process optionally triggers `forceArchive` via the Core-Skill client to persist any lingering skill buffers before clearing the cache. According to the source code in [`workbuddyHandler.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/workbuddyHandler.ts) (around line 1030), this archival step ensures active skill states are preserved to storage before the session store deletes the binding, preventing data loss while still allowing a fresh session context.

### How does MemoryProxy distinguish between a regular message and a reset command?

MemoryProxy imports `isSessionResetCommand` from [`mem-command/pre-intercept.js`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/mem-command/pre-intercept.js) at the start of `handleWorkbuddyEndpoint`. This function examines the request body for the specific text pattern `mem:session-reset` and validates it against the `agentSource` before allowing the reset to proceed, ensuring only authorized commands trigger cache invalidation.

### Can I reset the session cache without using the `mem:session-reset` command?

While the `mem:session-reset` command is the intended interface, you could theoretically achieve similar results by directly manipulating the session store bindings in [`store.js`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/store.js) or deleting entries via the binding repository. However, doing so bypasses the validation, archival, and proper state machine reset logic implemented in [`workbuddyHandler.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/workbuddyHandler.ts), potentially leaving orphaned skill states or inconsistent session metadata.

### What is the `resetEpoch` field in the session store?

When `store.set` initializes a fresh session after a reset, it includes `resetEpoch: Date.now()` and `resetFlow: true` in the session state object. These fields mark the timestamp of the reset operation and flag the session as having undergone a reset flow, allowing downstream handlers in the session initialization logic to handle the fresh context appropriately and distinguish it from standard session continuations.