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

middleware.ts

394 lines12.8 KB

1import { aiEventClient } from '@tanstack/ai-event-client'
2import type {
3 ChatMiddleware,
4 ChatMiddlewareConfig,
5 ChatMiddlewareContext,
6 ModelMessage,
7 StreamChunk,
8} from '@tanstack/ai'
9import type {
10 MemoryAdapter,
11 MemoryFact,
12 MemoryScope,
13 MemoryTurn,
14 RecallResult,
15 SaveReceipt,
16} from './types'
17​
18/**
19 * CUSTOM stream-event name carrying server-side memory state to the browser.
20 * The middleware injects one of these per turn (via `onChunk`); the client
21 * devtools bridge (`@tanstack/ai-client`) recognizes it and re-emits `memory:*`
22 * on the browser event bus. This is how server-side memory reaches the browser
23 * DevTools panel — server-emitted `aiEventClient` events never cross runtimes;
24 * everything the panel shows is re-derived client-side from the chat stream
25 * (mirrors how generation results ride `CUSTOM` events — see `GENERATION_EVENTS`).
26 */
27export const MEMORY_STATE_EVENT = 'memory:state'
28​
29/** Payload of the {@link MEMORY_STATE_EVENT} CUSTOM chunk. Captures memory state
30 * as of the turn's START — the snapshot reflects every prior turn's save; this
31 * turn's own save (deferred) surfaces in the next turn's snapshot. */
32export interface MemoryStateEventValue {
33 scope: MemoryScope
34 adapter: string
35 /** The recall query (last user text). */
36 query: string
37 /** Recall metrics for the operations timeline. */
38 recall: {
39 fragmentCount: number
40 hasTools: boolean
41 systemPromptChars: number
42 durationMs: number
43 }
44 /** Live store snapshot, when the adapter supports `inspect`/`listFacts`. */
45 snapshot?: {
46 takenAt: string
47 data: unknown
48 facts: Array<MemoryFact>
49 }
51​
52/**
53 * How the middleware participates in the run:
54 * - `'recall+save'` (default): recall on init (inject prompt + tools), save on finish.
55 * - `'save-only'`: skip recall entirely — persist the turn but never read/inject.
56 */
57export type MemoryMiddlewareRole = 'recall+save' | 'save-only'
58​
59export interface MemoryRecallInfo {
60 scope: MemoryScope
61 query: string
62 result: RecallResult
64​
65export interface MemorySaveInfo {
66 scope: MemoryScope
67 turn: MemoryTurn
68 receipts: Array<SaveReceipt>
70​
71export interface MemoryMiddlewareOptions {
72 /** The memory backend to recall from / save to. */
73 adapter: MemoryAdapter
74 /**
75 * Scope for every adapter call. The function form is the safer default for
76 * multi-tenant apps: derive scope per request from trusted, server-validated
77 * chat context — never from client input.
78 */
79 scope:
80 | MemoryScope
81 | ((ctx: ChatMiddlewareContext) => MemoryScope | Promise<MemoryScope>)
82 /** Participation role. Defaults to `'recall+save'`. */
83 role?: MemoryMiddlewareRole
84 /** Fired after `recall` completes (post-injection), for app telemetry. */
85 onRecall?: (info: MemoryRecallInfo) => void | Promise<void>
86 /** Fired after the deferred `save` completes, for app telemetry. */
87 onSave?: (info: MemorySaveInfo) => void | Promise<void>
89​
90/** Per-request scratch state, keyed by context in a module-level WeakMap so the
91 * same middleware instance is safe across concurrent `chat()` calls. */
92interface MemoryRequestState {
93 resolvedScope?: MemoryScope
94 lastUserText: string
95 /** Pending devtools transport chunk, injected once by the first `onChunk`. */
96 stateChunk?: { emitted: boolean; value: MemoryStateEventValue }
98​
99const stateByCtx = new WeakMap<ChatMiddlewareContext, MemoryRequestState>()
100​
101/**
102 * Server-side memory middleware. Recalls relevant memory into the prompt before
103 * the model runs, then defers `save` of the completed turn after it finishes.
104 * All extraction/ranking/rendering lives in the adapter — this middleware only
105 * wires `recall`/`save` into the chat lifecycle and emits devtools events.
106 */
107export function memoryMiddleware(
108 options: MemoryMiddlewareOptions,
109): ChatMiddleware {
110 const role = options.role ?? 'recall+save'
111​
112 async function resolveScope(
113 ctx: ChatMiddlewareContext,
114 state: MemoryRequestState,
115 ): Promise<MemoryScope> {
116 if (state.resolvedScope) return state.resolvedScope
117 state.resolvedScope =
118 typeof options.scope === 'function'
119 ? await options.scope(ctx)
120 : options.scope
121 return state.resolvedScope
122 }
123​
124 return {
125 name: `memory:${options.adapter.id}`,
126​
127 async onConfig(ctx, config) {
128 if (ctx.phase !== 'init') return
129​
130 const state: MemoryRequestState = { lastUserText: '' }
131 stateByCtx.set(ctx, state)
132​
133 state.lastUserText = getMessageText(findLastUserMessage(config.messages))
134 if (!state.lastUserText || role === 'save-only') return
135​
136 const startedAt = Date.now()
137 let scope: MemoryScope
138 let result: RecallResult
139 try {
140 scope = await resolveScope(ctx, state)
141 safeEmit('memory:retrieve:started', {
142 scope,
143 adapter: options.adapter.id,
144 query: state.lastUserText,
145 timestamp: startedAt,
146 })
147 result = await options.adapter.recall(scope, state.lastUserText)
148 } catch (error) {
149 safeEmit('memory:error', {
150 // Only attach scope when resolve already succeeded; otherwise omit
151 // (no empty-string / partial fake identity).
152 ...(state.resolvedScope ? { scope: state.resolvedScope } : {}),
153 adapter: options.adapter.id,
154 phase: 'recall',
155 error: errorInfo(error),
156 timestamp: Date.now(),
157 })
158 return
159 }
160​
161 const tools = result.tools ?? []
162 const recallMetrics = {
163 fragmentCount: result.fragments?.length ?? 0,
164 hasTools: tools.length > 0,
165 systemPromptChars: result.systemPrompt.length,
166 durationMs: Date.now() - startedAt,
167 }
168 safeEmit('memory:retrieve:completed', {
169 scope,
170 adapter: options.adapter.id,
171 ...recallMetrics,
172 timestamp: Date.now(),
173 })
174 await options.onRecall?.({ scope, query: state.lastUserText, result })
175​
176 // Stage the devtools transport chunk (recall metrics + current store
177 // snapshot). Injected into the stream by `onChunk` so it reaches the
178 // browser panel; see MEMORY_STATE_EVENT.
179 const snapshot = await gatherSnapshot(options.adapter, scope)
180 state.stateChunk = {
181 emitted: false,
182 value: {
183 scope,
184 adapter: options.adapter.id,
185 query: state.lastUserText,
186 recall: recallMetrics,
187 ...(snapshot ? { snapshot } : {}),
188 },
189 }
190​
191 const memoryPrompts = [result.toolGuidance ?? '', result.systemPrompt]
192 const additions = memoryPrompts.filter((p) => p.length > 0)
193 if (additions.length === 0 && tools.length === 0) return
194​
195 const existingToolNames = new Set(config.tools.map((tool) => tool.name))
196 const extraTools = tools.filter(
197 (tool) => !existingToolNames.has(tool.name),
198 )
199​
200 return {
201 systemPrompts: [...config.systemPrompts, ...additions],
202 tools:
203 extraTools.length > 0
204 ? [...config.tools, ...extraTools]
205 : config.tools,
206 } satisfies Partial<ChatMiddlewareConfig>
207 },
208​
209 onChunk(ctx, chunk) {
210 // Inject the staged memory-state chunk exactly once, riding alongside the
211 // first stream chunk (typically RUN_STARTED) so the browser devtools sees
212 // it. Returning an array expands the stream; see ChatMiddleware.onChunk.
213 const state = stateByCtx.get(ctx)
214 if (!state?.stateChunk || state.stateChunk.emitted) return
215 state.stateChunk.emitted = true
216 const custom: StreamChunk = {
217 type: 'CUSTOM',
218 name: MEMORY_STATE_EVENT,
219 value: state.stateChunk.value,
220 timestamp: Date.now(),
221 }
222 return [chunk, custom]
223 },
224​
225 onFinish(ctx, info) {
226 const state = stateByCtx.get(ctx)
227 stateByCtx.delete(ctx)
228 const userText =
229 state?.lastUserText || getMessageText(findLastUserMessage(ctx.messages))
230 const assistant = info.content
231 if (!userText || !assistant) return
232 const scope = state?.resolvedScope
233​
234 ctx.defer(
235 (async () => {
236 // Resolve scope defensively — a throwing resolver must not escape the
237 // terminal hook. Memory failures are always non-fatal + observable.
238 let resolved: MemoryScope
239 try {
240 resolved =
241 scope ?? (await resolveScope(ctx, { lastUserText: userText }))
242 } catch (error) {
243 safeEmit('memory:error', {
244 adapter: options.adapter.id,
245 phase: 'save',
246 error: errorInfo(error),
247 timestamp: Date.now(),
248 })
249 return
250 }
251​
252 const turn: MemoryTurn = { user: userText, assistant }
253 const startedAt = Date.now()
254 safeEmit('memory:persist:started', {
255 scope: resolved,
256 adapter: options.adapter.id,
257 timestamp: startedAt,
258 })
259 let receipts: Array<SaveReceipt>
260 try {
261 receipts = await options.adapter.save(resolved, turn)
262 } catch (error) {
263 receipts = [{ ok: false, error: String(error) }]
264 safeEmit('memory:error', {
265 scope: resolved,
266 adapter: options.adapter.id,
267 phase: 'save',
268 error: errorInfo(error),
269 timestamp: Date.now(),
270 })
271 }
272 safeEmit('memory:persist:completed', {
273 scope: resolved,
274 adapter: options.adapter.id,
275 receiptCount: receipts.length,
276 okCount: receipts.filter((r) => r.ok).length,
277 durationMs: Date.now() - startedAt,
278 timestamp: Date.now(),
279 })
280 await emitSnapshot(options.adapter, resolved)
281 await options.onSave?.({ scope: resolved, turn, receipts })
282 })(),
283 )
284 },
285 }
287​
288// ===========================
289// Internals
290// ===========================
291​
292/**
293 * Read the adapter's current stored state via the optional `inspect`/`listFacts`
294 * introspection methods. Returns `undefined` for adapters that don't implement
295 * `inspect` (they degrade to the metrics-only timeline). Fully guarded:
296 * introspection must never affect chat.
297 */
298async function gatherSnapshot(
299 adapter: MemoryAdapter,
300 scope: MemoryScope,
301): Promise<
302 { takenAt: string; data: unknown; facts: Array<MemoryFact> } | undefined
303> {
304 if (!adapter.inspect) return undefined
305 try {
306 const snapshot = await adapter.inspect(scope)
307 const facts = (await adapter.listFacts?.(scope)) ?? []
308 return { takenAt: snapshot.takenAt, data: snapshot.data, facts }
309 } catch {
310 // ignored — introspection is best-effort telemetry.
311 return undefined
312 }
314​
315/**
316 * DevTools-only: after a save, emit the adapter's current stored state on the
317 * (in-process) event bus, so a devtools consumer running in the SAME runtime as
318 * the chat (client-side execution / server-side listener) sees "what's in
319 * memory". For the standard server-side topology, the browser panel instead
320 * gets state via the {@link MEMORY_STATE_EVENT} stream chunk (see `onChunk`).
321 */
322async function emitSnapshot(
323 adapter: MemoryAdapter,
324 scope: MemoryScope,
325): Promise<void> {
326 const snapshot = await gatherSnapshot(adapter, scope)
327 if (!snapshot) return
328 safeEmit('memory:snapshot', {
329 scope,
330 adapter: adapter.id,
331 ...snapshot,
332 timestamp: Date.now(),
333 })
335​
336function findLastUserMessage(
337 messages: ReadonlyArray<ModelMessage>,
338): ModelMessage | undefined {
339 for (let i = messages.length - 1; i >= 0; i--) {
340 const message = messages[i]
341 if (message && message.role === 'user') return message
342 }
343 return undefined
345​
346/**
347 * Extract plain text from a `ModelMessage`. Text lives on `part.content` for
348 * `TextPart`; bare strings in the content array are tolerated. All other
349 * content kinds (tool-call, image, …) yield '' so they don't pollute the
350 * recall query.
351 */
352function getMessageText(message?: ModelMessage): string {
353 if (!message) return ''
354 if (typeof message.content === 'string') return message.content
355 if (Array.isArray(message.content)) {
356 return message.content
357 .map((part) => {
358 if (typeof part === 'string') return part
359 if (part.type === 'text' && typeof part.content === 'string') {
360 return part.content
361 }
362 return ''
363 })
364 .filter(Boolean)
365 .join('\n')
366 }
367 return ''
369​
370function errorInfo(error: unknown): { name: string; message: string } {
371 if (error instanceof Error)
372 return { name: error.name, message: error.message }
373 if (
374 error &&
375 typeof error === 'object' &&
376 'name' in error &&
377 typeof error.name === 'string'
378 ) {
379 return {
380 name: error.name,
381 message: String((error as { message?: unknown }).message ?? error),
382 }
383 }
384 return { name: 'Error', message: String(error) }
386​
387/** Fire-and-forget devtools emit — telemetry failures must never affect chat. */
388function safeEmit(...args: Parameters<typeof aiEventClient.emit>): void {
389 try {
390 aiEventClient.emit(...args)
391 } catch {
392 // ignored — telemetry must not affect chat behaviour
393 }