Open History to see the last commit
1import type {
2 MemoryErrorEvent,
3 MemoryPersistCompletedEvent,
4 MemoryPersistStartedEvent,
5 MemoryRetrieveCompletedEvent,
6 MemoryRetrieveStartedEvent,
7 MemoryScopeLite,
8 MemorySnapshotEvent,
9} from '@tanstack/ai-event-client'
10
11/**
12 * DevTools-side accumulator for the `memory:*` event stream. Kept as a set of
13 * pure reducers (mirroring `hook-registry.ts`) so the mapping from events →
14 * view state is unit-testable in isolation, without a Solid store.
15 *
16 * Memory is keyed by composite scope (`tenantId`/`userId`/`threadId`), NOT by
17 * hook — several hooks can share one scope. The `MemoryPanel` reads a single
18 * `MemoryScopeState` by key; the per-hook tab just resolves which key to show.
19 */
20
21/** One row in a scope's operations timeline. */
22export interface MemoryEventRecord {
23 id: string
24 type:
25 | 'retrieve:started'
26 | 'retrieve:completed'
27 | 'persist:started'
28 | 'persist:completed'
29 | 'error'
30 timestamp: number
31 adapter: string
32 /** recall:started — the recall query (last user text). */
33 query?: string
34 /** recall:completed. */
35 fragmentCount?: number
36 hasTools?: boolean
37 systemPromptChars?: number
38 /** persist:completed. */
39 receiptCount?: number
40 okCount?: number
41 /** recall:completed / persist:completed. */
42 durationMs?: number
43 /** error. */
44 phase?: 'recall' | 'save'
45 error?: { name: string; message: string }
46}
47
48/** A flat fact row, mirroring `MemoryFact` from `@tanstack/ai-memory`. */
49export interface MemoryFactRecord {
50 id: string
51 text: string
52 source?: string
53 createdAt?: string
54}
55
56/** Latest `inspect()` + `listFacts()` snapshot pushed via `memory:snapshot`. */
57export interface MemorySnapshotRecord {
58 takenAt: string
59 data: unknown
60 facts: Array<MemoryFactRecord>
61}
62
63/** Everything known about memory for a single composite scope. */
64export interface MemoryScopeState {
65 key: string
66 threadId: string
67 userId?: string
68 tenantId?: string
69 namespace?: string
70 /** Most recent adapter id seen for this scope. */
71 adapter?: string
72 events: Array<MemoryEventRecord>
73 snapshot?: MemorySnapshotRecord
74 lastActivity: number
75}
76
77export interface MemoryRegistryState {
78 scopes: Record<string, MemoryScopeState>
79}
80
81export function createMemoryRegistryState(): MemoryRegistryState {
82 return { scopes: {} }
83}
84
85/**
86 * Escape `:` / `\` / `_` so composite keys cannot collide when a dim contains
87 * the separator or the unset sentinel (mirrors redis scope-key hardening).
88 */
89function escapeScopeDim(value: string): string {
90 return value.replace(/[\\:_]/g, '\\$&')
91}
92
93/** Unset optional dims serialize as `_` (same convention as the redis adapter). */
94function scopeDim(value: string | undefined): string {
95 return value != null && value.length > 0 ? escapeScopeDim(value) : '_'
96}
97
98/**
99 * Stable scope key:
100 * `{tenantId|_}:{userId|_}:{threadId}:{namespace|_}`.
101 * Absent scope (e.g. `memory:error` before resolve) buckets to `(unknown)`.
102 */
103export function memoryScopeKey(scope: MemoryScopeLite | undefined): string {
104 if (!scope) return '(unknown)'
105 return `${scopeDim(scope.tenantId)}:${scopeDim(scope.userId)}:${escapeScopeDim(scope.threadId)}:${scopeDim(scope.namespace)}`
106}
107
108/** Human-readable label for the Memory panel scope picker. */
109export function memoryScopeLabel(entry: MemoryScopeState): string {
110 if (entry.key === '(unknown)' || !entry.threadId) return '(unknown)'
111 const parts = [
112 entry.tenantId,
113 entry.userId,
114 entry.threadId,
115 entry.namespace,
116 ].filter((p): p is string => p != null && p.length > 0)
117 return parts.join(' · ')
118}
119
120const MAX_EVENTS_PER_SCOPE = 200
121
122function ensureScope(
123 state: MemoryRegistryState,
124 scope: MemoryScopeLite | undefined,
125): MemoryScopeState {
126 const key = memoryScopeKey(scope)
127 let entry = state.scopes[key]
128 if (!entry) {
129 entry = {
130 key,
131 threadId: scope?.threadId ?? '',
132 userId: scope?.userId,
133 tenantId: scope?.tenantId,
134 namespace: scope?.namespace,
135 events: [],
136 lastActivity: 0,
137 }
138 state.scopes[key] = entry
139 }
140 // Only merge metadata when we have a real scope (not the unscoped error bucket).
141 if (scope) {
142 if (scope.userId) entry.userId = scope.userId
143 if (scope.tenantId) entry.tenantId = scope.tenantId
144 if (scope.namespace) entry.namespace = scope.namespace
145 }
146 return entry
147}
148
149let fallbackCounter = 0
150
151function eventId(
152 payload: { eventId?: string },
153 type: string,
154 ts: number,
155): string {
156 if (payload.eventId && payload.eventId.length > 0) return payload.eventId
157 return `${type}:${ts}:${fallbackCounter++}`
158}
159
160type MemoryEventPayload =
161 | ({ type: 'retrieve:started' } & MemoryRetrieveStartedEvent)
162 | ({ type: 'retrieve:completed' } & MemoryRetrieveCompletedEvent)
163 | ({ type: 'persist:started' } & MemoryPersistStartedEvent)
164 | ({ type: 'persist:completed' } & MemoryPersistCompletedEvent)
165 | ({ type: 'error' } & MemoryErrorEvent)
166
167/** Append one `memory:*` operation event to its scope's timeline. */
168export function applyMemoryEvent(
169 state: MemoryRegistryState,
170 event: MemoryEventPayload,
171): void {
172 const entry = ensureScope(state, event.scope)
173 entry.adapter = event.adapter
174 entry.lastActivity = Math.max(entry.lastActivity, event.timestamp)
175
176 const record: MemoryEventRecord = {
177 id: eventId(event, event.type, event.timestamp),
178 type: event.type,
179 timestamp: event.timestamp,
180 adapter: event.adapter,
181 }
182 switch (event.type) {
183 case 'retrieve:started':
184 record.query = event.query
185 break
186 case 'retrieve:completed':
187 record.fragmentCount = event.fragmentCount
188 record.hasTools = event.hasTools
189 record.systemPromptChars = event.systemPromptChars
190 record.durationMs = event.durationMs
191 break
192 case 'persist:completed':
193 record.receiptCount = event.receiptCount
194 record.okCount = event.okCount
195 record.durationMs = event.durationMs
196 break
197 case 'error':
198 record.phase = event.phase
199 record.error = event.error
200 break
201 case 'persist:started':
202 break
203 }
204
205 entry.events.push(record)
206 if (entry.events.length > MAX_EVENTS_PER_SCOPE) {
207 entry.events.splice(0, entry.events.length - MAX_EVENTS_PER_SCOPE)
208 }
209}
210
211/** Replace a scope's stored-state snapshot from a `memory:snapshot` event. */
212export function applyMemorySnapshot(
213 state: MemoryRegistryState,
214 event: MemorySnapshotEvent,
215): void {
216 const entry = ensureScope(state, event.scope)
217 entry.adapter = event.adapter
218 entry.lastActivity = Math.max(entry.lastActivity, event.timestamp)
219 entry.snapshot = {
220 takenAt: event.takenAt,
221 data: event.data,
222 facts: event.facts,
223 }
224}
225
226export function clearMemoryRegistry(state: MemoryRegistryState): void {
227 state.scopes = {}
228}