Agent Skills › TanStack/ai › tanstack-ai-memory

tanstack-ai-memory

GitHub

用于在 TanStack AI chat() 中集成服务端记忆中间件,支持跨会话上下文持久化。涵盖适配器选型(如 Redis、mem0)、作用域安全配置及 recall/save 生命周期管理。

packages/ai-memory/skills/tanstack-ai-memory/SKILL.md TanStack/ai

Trigger Scenarios

需要为 AI 聊天添加跨会话记忆功能 集成 TanStack AI 记忆中间件或适配器 配置记忆存储的作用域与安全策略

Install

npx skills add TanStack/ai --skill tanstack-ai-memory -g -y
More Options

Non-standard path

npx skills add https://github.com/TanStack/ai/tree/main/packages/ai-memory/skills/tanstack-ai-memory -g -y

Use without installing

npx skills use TanStack/ai@tanstack-ai-memory

指定 Agent (Claude Code)

npx skills add TanStack/ai --skill tanstack-ai-memory -a claude-code -g -y

安装 repo 全部 skill

npx skills add TanStack/ai --all -g -y

预览 repo 内 skill

npx skills add TanStack/ai --list

SKILL.md

Frontmatter
{
    "name": "tanstack-ai-memory",
    "description": "Use when wiring memoryMiddleware from @tanstack\/ai-memory into a chat() call — covers the recall\/save adapter contract, scope shape and server-side scope security, the recall-inject \/ deferred-save lifecycle, choosing an adapter (inMemory, redis, hindsight, mem0, honcho), and devtools events."
}

TanStack AI Memory Middleware

Use this when adding server-side memory to a chat() call. Everything lives in @tanstack/ai-memory. A memory adapter is a single contract with two verbs — recall and save — and the middleware is thin: it recalls into the system prompt before the model runs and defers save after the turn finishes.

When to reach for it

  • A user expects "remember what I told you last time."
  • Per-user or per-thread context that must survive across sessions.
  • A hosted memory service (mem0, Honcho, Hindsight).

Do NOT use this just to keep recent messages — that's the messages array on chat(). Memory is for cross-turn / cross-session recall, not within-turn history.

Wire it up

import { chat, toServerSentEventsResponse } from '@tanstack/ai'
import { openaiText } from '@tanstack/ai-openai'
import { memoryMiddleware } from '@tanstack/ai-memory'
import { inMemory } from '@tanstack/ai-memory/in-memory'
import { requireSession } from './auth'

const memory = inMemory() // dev/tests only — see the in-memory skill

export async function POST(request: Request) {
  const { messages } = await request.json()
  // Resolved by your auth layer from cookies/headers — never from the request body.
  const session = await requireSession(request)

  const stream = chat({
    adapter: openaiText('gpt-5.5'),
    messages,
    context: { session },
    middleware: [
      memoryMiddleware({
        adapter: memory,
        // Derive scope server-side from trusted session state.
        scope: () => ({ threadId: session.threadId, userId: session.userId }),
      }),
    ],
  })
  return toServerSentEventsResponse(stream)
}

memoryMiddleware options: adapter, scope (static or a function of ctx), role ('recall+save' default, or 'save-only'), and onRecall / onSave telemetry callbacks.

The contract

import type {
  MemoryFact,
  MemoryScope,
  MemorySnapshot,
  MemoryTurn,
  RecallResult,
  SaveReceipt,
} from '@tanstack/ai-memory'

interface MemoryAdapter {
  readonly id: string
  recall: (scope: MemoryScope, query: string) => Promise<RecallResult> // { systemPrompt, fragments?, tools?, toolGuidance? }
  save: (scope: MemoryScope, turn: MemoryTurn) => Promise<Array<SaveReceipt>> // turn = { user, assistant }; extraction lives HERE
  inspect?: (scope: MemoryScope) => Promise<MemorySnapshot> // optional (devtools)
  listFacts?: (scope: MemoryScope) => Promise<Array<MemoryFact>> // optional (devtools)
}
  • recall decides relevance and renders a systemPrompt; it may also return tools + toolGuidance to hand the model direct control of memory (hindsight does this).
  • save owns extraction — turning the raw turn into whatever gets persisted.

Scope security

MemoryScope is an alias of the shared Scope type from @tanstack/ai: { threadId, userId?, tenantId?, namespace? }. It is the isolation boundary. Never trust a client-supplied userId/threadId. Resolve scope server-side from session/auth and pass the validated session through chat({ context: { session } }). If you accept a thread id from the request body, validate it belongs to the session user BEFORE using it.

Adapters

  • inMemory() / redis() — exact match on threadId + optional userId/tenantId (namespace ignored). Redis index keys include all three segments.
  • hindsight() — bank {tenant|_}__{user}__{threadId}.
  • mem0() — user_id + run_id (threadId); no tenantId.
  • honcho() — session {tenant|_}__{threadId}; peer tenant-prefixed when set.
  • Custom — implement recall/save and run runMemoryAdapterContract from @tanstack/ai-memory/testkit.

Failure modes

Memory failures are non-fatal: a throwing recall or save emits memory:error and the run continues with degraded memory. Streaming is never blocked; a failed save never fails the turn.

Devtools

Five events on aiEventClient (from @tanstack/ai-event-client): memory:retrieve:started / :completed, memory:persist:started / :completed, memory:error (phase: 'recall' | 'save'). Payloads carry the adapter id and fragment/receipt counts, not full memory text. Error events include scope only when it was already resolved; if the resolver threw, scope is omitted.

Version History

  • 645757a Current 2026-09-22 03:43

    发布 @tanstack/ai-memory/testkit 包以支持适配器合约测试;修复代码块类型检查及 API 描述不一致问题。

  • 05280a5 2026-07-30 23:52

Same Skill Collection

.agents/skills/add-example-tutorial/SKILL.md
.agents/skills/gap-analysis/SKILL.md
.agents/skills/i-have-adhd/SKILL.md
.agents/skills/pr-description/SKILL.md
.claude/skills/add-example-tutorial/SKILL.md
.claude/skills/gap-analysis/SKILL.md
.claude/skills/i-have-adhd/SKILL.md
.claude/skills/pr-description/SKILL.md
.grok/skills/add-example-tutorial/SKILL.md
.grok/skills/gap-analysis/SKILL.md
.grok/skills/i-have-adhd/SKILL.md
.grok/skills/pr-description/SKILL.md
examples/ts-remix-chat/.agents/skills/remix/SKILL.md
packages/ai-code-mode/skills/ai-code-mode/SKILL.md
packages/ai-mcp/skills/ai-mcp/SKILL.md
packages/ai-memory/skills/tanstack-ai-memory-hindsight/SKILL.md
packages/ai-memory/skills/tanstack-ai-memory-honcho/SKILL.md
packages/ai-memory/skills/tanstack-ai-memory-in-memory/SKILL.md
packages/ai-memory/skills/tanstack-ai-memory-mem0/SKILL.md
packages/ai-memory/skills/tanstack-ai-memory-redis/SKILL.md
packages/ai-persistence/skills/ai-persistence/build-cloudflare-adapter/SKILL.md
packages/ai-persistence/skills/ai-persistence/build-cloudflare-artifact-store/SKILL.md
packages/ai-persistence/skills/ai-persistence/build-custom-adapter/SKILL.md
packages/ai-persistence/skills/ai-persistence/build-drizzle-adapter/SKILL.md
packages/ai-persistence/skills/ai-persistence/build-prisma-adapter/SKILL.md
packages/ai-persistence/skills/ai-persistence/server/SKILL.md
packages/ai-persistence/skills/ai-persistence/SKILL.md
packages/ai-persistence/skills/ai-persistence/stores/SKILL.md
packages/ai/skills/ai-core/ag-ui-protocol/SKILL.md
packages/ai/skills/ai-core/chat-experience/SKILL.md
packages/ai/skills/ai-core/custom-backend-integration/SKILL.md
packages/ai/skills/ai-core/debug-logging/SKILL.md
packages/ai/skills/ai-core/locks/SKILL.md
packages/ai/skills/ai-core/middleware/SKILL.md
packages/ai/skills/ai-core/SKILL.md
packages/ai/skills/ai-core/tool-calling/SKILL.md
testing/panel/skills/emoji-storyteller/SKILL.md
testing/panel/skills/haiku/SKILL.md
testing/panel/skills/pirate-speak/SKILL.md
.agents/skills/bugfix-pr/SKILL.md
.agents/skills/docs/SKILL.md
.agents/skills/ponytail/SKILL.md
.agents/skills/pr-sweep/SKILL.md
.agents/skills/simple-english/SKILL.md
.agents/skills/triage-github/SKILL.md
.claude/skills/bugfix-pr/SKILL.md
.claude/skills/docs/SKILL.md
.claude/skills/ponytail/SKILL.md
.claude/skills/pr-sweep/SKILL.md

Metadata

Files
0
Version
3e30cde
Hash
8631c2e9
Indexed
2026-07-30 23:52

Home - Wiki
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-09-27 17:14
浙ICP备14020137号-1