Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

memory-store.ts

51 lines2.0 KB

1import { inMemory } from '@tanstack/ai-memory/in-memory'
2import type { MemoryScope, RecallResult } from '@tanstack/ai-memory'
3​
4/**
5 * Process-local memory backing the `/memory` demo page.
6 *
7 * `inMemory()` stores everything in an in-process `Map`, so the chat route
8 * (which writes via `memoryMiddleware`) and the inspect route (which reads via
9 * `inspect`/`listFacts`) MUST share this exact singleton — a second
10 * `inMemory()` call would have its own, empty store.
11 *
12 * Defaults are deliberate: no `embedder`/`extract`, so `save` just stores the
13 * raw user/assistant turn (kind `message`). That keeps the demo zero-dep and
14 * makes the stored content legible in the panel. To demo derived facts or
15 * semantic recall, pass `{ extract, embedder }` to `inMemory()` here.
16 */
17export const memoryAdapter = inMemory()
18​
19/**
20 * Server-trusted demo identity. Never accept `userId` / `tenantId` from the
21 * client — the panel is a local demo without real auth, so these constants are
22 * the isolation dims. Production apps must derive every Scope field from a
23 * validated session.
24 */
25export const PANEL_MEMORY_USER = 'panel-demo-user'
26export const PANEL_MEMORY_TENANT = 'panel-demo'
27​
28/**
29 * Build the middleware/inspect scope for a client-chosen thread. User and
30 * tenant come only from the server constants above.
31 */
32export function panelMemoryScope(threadId: string): MemoryScope {
33 return {
34 threadId,
35 userId: PANEL_MEMORY_USER,
36 tenantId: PANEL_MEMORY_TENANT,
37 }
39​
40/** Composite key matching built-in adapter isolation dims (not threadId alone). */
41export function panelScopeKey(scope: MemoryScope): string {
42 return `${scope.tenantId ?? '_'}|${scope.userId ?? '_'}|${scope.threadId}`
44​
45/**
46 * Records what the last `recall` injected for each composite scope, so the
47 * page can show "what memory fed into this turn". Populated from the
48 * middleware's `onRecall` callback in the chat route; read by the inspect
49 * route.
50 */
51export const lastRecallByThread = new Map<string, RecallResult>()