@mastra/mcp-docs-server 1.3.13-alpha.16 → 1.3.13-alpha.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.docs/docs/auth/custom-auth-provider.md +66 -0
- package/.docs/docs/auth/jwt.md +1 -1
- package/.docs/docs/connections/mcp.md +2 -65
- package/.docs/docs/memory/multi-user-threads.md +57 -127
- package/.docs/docs/memory/observational-memory.md +196 -756
- package/.docs/docs/memory/overview.md +4 -0
- package/.docs/docs/server/mcp.md +315 -0
- package/.docs/docs/server/request-context.md +35 -0
- package/.docs/docs/studio/deployment.md +0 -1
- package/.docs/docs/studio/overview.md +2 -4
- package/.docs/reference/auth/jwt.md +26 -2
- package/.docs/reference/configuration.md +64 -0
- package/.docs/reference/index.md +1 -0
- package/.docs/reference/memory/observational-memory.md +350 -151
- package/.docs/reference/rag/chunk.md +1 -1
- package/.docs/reference/rag/graph-rag-guide.md +3 -1
- package/.docs/reference/server/dispatch-route.md +124 -0
- package/.docs/reference/server/elysia-adapter.md +1 -1
- package/.docs/reference/server/express-adapter.md +1 -1
- package/.docs/reference/server/fastify-adapter.md +1 -1
- package/.docs/reference/server/hono-adapter.md +1 -1
- package/.docs/reference/server/invoke-route.md +10 -0
- package/.docs/reference/server/koa-adapter.md +1 -1
- package/.docs/reference/server/nestjs-adapter.md +1 -1
- package/package.json +3 -3
|
@@ -6,7 +6,9 @@
|
|
|
6
6
|
|
|
7
7
|
**Added in:** `@mastra/memory@1.1.0`
|
|
8
8
|
|
|
9
|
-
Observational Memory (OM)
|
|
9
|
+
Observational Memory (OM) lets an agent work in one thread for as long as the task takes, with a context that stays small, focused and prompt-cache friendly. An **Observer** agent turns older messages into short, dated observations in the background, and a **Reflector** agent condenses those observations when they grow. The agent sees its recent messages in full and everything earlier as observations.
|
|
10
|
+
|
|
11
|
+
Use OM for any agent that does more than a one-off summary or a single workflow step. Every agent that takes multiple steps benefits: chat assistants, coding agents, browser agents, support threads that run for hours.
|
|
10
12
|
|
|
11
13
|
## Quickstart
|
|
12
14
|
|
|
@@ -36,28 +38,7 @@ yarn add @mastra/memory@latest @mastra/libsql@latest
|
|
|
36
38
|
bun add @mastra/memory@latest @mastra/libsql@latest
|
|
37
39
|
```
|
|
38
40
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
```typescript
|
|
42
|
-
import { Memory } from '@mastra/memory'
|
|
43
|
-
import { Agent } from '@mastra/core/agent'
|
|
44
|
-
|
|
45
|
-
export const agent = new Agent({
|
|
46
|
-
id: 'my-agent',
|
|
47
|
-
name: 'my-agent',
|
|
48
|
-
instructions: 'You are a helpful assistant.',
|
|
49
|
-
model: 'openai/gpt-6-luna',
|
|
50
|
-
memory: new Memory({
|
|
51
|
-
options: {
|
|
52
|
-
observationalMemory: true,
|
|
53
|
-
},
|
|
54
|
-
}),
|
|
55
|
-
})
|
|
56
|
-
```
|
|
57
|
-
|
|
58
|
-
**For AI agents:** Using Observational Memory requires a storage provider! You either need to set it on the Mastra instance at `src/mastra/index.ts` or pass it to the Agent constructor.
|
|
59
|
-
|
|
60
|
-
The following script creates a local LibSQL database and enables Observational Memory before using one resource and thread across two agent calls:
|
|
41
|
+
OM needs storage that supports it (`@mastra/libsql`, `@mastra/pg`, `@mastra/mysql`, `@mastra/mongodb`, `@mastra/convex` or `@mastra/oracledb`), a thread for every call, and `observationalMemory: true`. This script stores memory in a local LibSQL file and calls the agent twice on one thread:
|
|
61
42
|
|
|
62
43
|
```typescript
|
|
63
44
|
import { Agent } from '@mastra/core/agent'
|
|
@@ -70,9 +51,7 @@ const memory = new Memory({
|
|
|
70
51
|
url: 'file:./memory.db',
|
|
71
52
|
}),
|
|
72
53
|
options: {
|
|
73
|
-
observationalMemory:
|
|
74
|
-
model: 'openai/gpt-6-luna',
|
|
75
|
-
},
|
|
54
|
+
observationalMemory: true,
|
|
76
55
|
},
|
|
77
56
|
})
|
|
78
57
|
|
|
@@ -89,384 +68,39 @@ const memoryOptions = {
|
|
|
89
68
|
thread: 'conversation-123',
|
|
90
69
|
}
|
|
91
70
|
|
|
92
|
-
const
|
|
71
|
+
const first = await agent.generate('Remember that my favorite color is blue.', {
|
|
93
72
|
memory: memoryOptions,
|
|
94
73
|
})
|
|
95
|
-
console.log(
|
|
74
|
+
console.log(first.text)
|
|
96
75
|
|
|
97
|
-
const
|
|
76
|
+
const second = await agent.generate('What is my favorite color?', {
|
|
98
77
|
memory: memoryOptions,
|
|
99
78
|
})
|
|
100
|
-
console.log(
|
|
101
|
-
```
|
|
102
|
-
|
|
103
|
-
The `resource` identifies the user or entity, while the `thread` identifies the conversation. Reuse both values to continue the same conversation. Observational Memory processes the stored history as it grows and replaces older messages with observations when its activation conditions are met.
|
|
104
|
-
|
|
105
|
-
The agent now has humanlike long-term memory that persists across conversations. Setting `observationalMemory: true` uses automatic model selection. To use a specific model, pass it in the config object:
|
|
106
|
-
|
|
107
|
-
```typescript
|
|
108
|
-
const memory = new Memory({
|
|
109
|
-
options: {
|
|
110
|
-
observationalMemory: {
|
|
111
|
-
model: 'deepseek/deepseek-flash',
|
|
112
|
-
},
|
|
113
|
-
},
|
|
114
|
-
})
|
|
115
|
-
```
|
|
116
|
-
|
|
117
|
-
See [configuration options](https://mastra.ai/reference/memory/observational-memory) for full API details.
|
|
118
|
-
|
|
119
|
-
> **Warning:** When you use OM with a client application, send **only the new message** from the client instead of the full conversation history.
|
|
120
|
-
>
|
|
121
|
-
> Observational memory still relies on stored conversation history. Sending the full history is redundant and can cause message ordering bugs when client-side timestamps conflict with stored timestamps. Mastra filters client-echoed history before loading stored messages and uses the stored copy as the base when message IDs match, preserving stored timestamps and provider metadata while retaining new tool results.
|
|
122
|
-
>
|
|
123
|
-
> If you assemble the request input yourself and need it processed exactly as sent, set `retainFullInput: true` on `memory.options` for that call, or in the memory constructor options to apply it agent-wide. This disables that filtering. History still loads underneath. Every input message that isn't already stored is saved to the thread, including few-shot examples.
|
|
124
|
-
>
|
|
125
|
-
> For an AI SDK example, see [Using Mastra Memory](https://mastra.ai/integrations/agentic-ui/ai-sdk-ui).
|
|
126
|
-
|
|
127
|
-
> **Note:** OM currently only supports `@mastra/pg`, `@mastra/libsql`, `@mastra/mysql`, `@mastra/mongodb`, `@mastra/convex`, and `@mastra/oracledb` storage adapters. It uses background agents for managing memory. When no model is set, the default is `model: 'auto'`.
|
|
128
|
-
|
|
129
|
-
### Automatic models in Mastra Code and Factory
|
|
130
|
-
|
|
131
|
-
Mastra Code and Factory surface the same automatic selection as a per-role **Auto** option in their settings.
|
|
132
|
-
|
|
133
|
-
An automatic Observer or Reflector follows the active main model provider. Mastra Code uses that provider's built-in low-cost Observational Memory model when one is configured. For custom providers and providers without a built-in choice, it uses the active main model. The effective model is resolved when the role runs, so changing the main model doesn't rewrite the saved automatic selection.
|
|
134
|
-
|
|
135
|
-
Select an explicit model to pin one role independently. Reset that role to **Auto** to resume following the main model provider. Existing saved concrete model IDs remain explicit until you reset them.
|
|
136
|
-
|
|
137
|
-
Factory stores automatic intent separately from the effective model shown in settings. A missing provider credential can mark that effective model unavailable, but it doesn't replace the saved selection or prevent Factory from starting.
|
|
138
|
-
|
|
139
|
-
## Temporal gap markers
|
|
140
|
-
|
|
141
|
-
Temporal gap markers insert a short reminder before a new user message when enough time has passed since the previous message in the thread. They help the agent and the UI see that the conversation resumed after a useful pause.
|
|
142
|
-
|
|
143
|
-
Temporal gap markers are off by default. Enable them with `temporalMarkers: true` in the `observationalMemory` config:
|
|
144
|
-
|
|
145
|
-
```typescript
|
|
146
|
-
import { Memory } from '@mastra/memory'
|
|
147
|
-
import { Agent } from '@mastra/core/agent'
|
|
148
|
-
|
|
149
|
-
export const agent = new Agent({
|
|
150
|
-
id: 'my-agent',
|
|
151
|
-
name: 'my-agent',
|
|
152
|
-
instructions: 'You are a helpful assistant.',
|
|
153
|
-
model: 'openai/gpt-6-luna',
|
|
154
|
-
memory: new Memory({
|
|
155
|
-
options: {
|
|
156
|
-
observationalMemory: {
|
|
157
|
-
model: 'auto',
|
|
158
|
-
temporalMarkers: true,
|
|
159
|
-
},
|
|
160
|
-
},
|
|
161
|
-
}),
|
|
162
|
-
})
|
|
163
|
-
```
|
|
164
|
-
|
|
165
|
-
Mastra inserts a temporal gap marker when the gap is at least 10 minutes. The marker is stored in memory and also emitted as a transient reminder event, so clients can render it as a lightweight timeline hint.
|
|
166
|
-
|
|
167
|
-
The observer also sees these markers when it processes the thread. The observations it writes can anchor memories to when they happened (for example, "User asked about deployment after a 2-day gap").
|
|
168
|
-
|
|
169
|
-
See [the API reference](https://mastra.ai/reference/memory/observational-memory) for the full configuration shape.
|
|
170
|
-
|
|
171
|
-
## Early activation
|
|
172
|
-
|
|
173
|
-
OM can activate buffered observations before the token threshold is reached. This is useful when a prompt cache is likely to expire, or when the agent changes model providers.
|
|
174
|
-
|
|
175
|
-
Top-level early activation settings apply to observations by default:
|
|
176
|
-
|
|
177
|
-
```typescript
|
|
178
|
-
import { Memory } from '@mastra/memory'
|
|
179
|
-
|
|
180
|
-
const memory = new Memory({
|
|
181
|
-
options: {
|
|
182
|
-
observationalMemory: {
|
|
183
|
-
model: 'auto',
|
|
184
|
-
activateAfterIdle: 'auto',
|
|
185
|
-
activateOnProviderChange: true,
|
|
186
|
-
},
|
|
187
|
-
},
|
|
188
|
-
})
|
|
189
|
-
```
|
|
190
|
-
|
|
191
|
-
Use nested `observation` and `reflection` settings for per-phase control. Reflection early activation is opt-in, so top-level settings affect only observations.
|
|
192
|
-
|
|
193
|
-
```typescript
|
|
194
|
-
import { Memory } from '@mastra/memory'
|
|
195
|
-
|
|
196
|
-
const memory = new Memory({
|
|
197
|
-
options: {
|
|
198
|
-
observationalMemory: {
|
|
199
|
-
model: 'auto',
|
|
200
|
-
activateAfterIdle: '5m',
|
|
201
|
-
observation: {
|
|
202
|
-
activateAfterIdle: false,
|
|
203
|
-
},
|
|
204
|
-
reflection: {
|
|
205
|
-
activateAfterIdle: '10m',
|
|
206
|
-
activateOnProviderChange: true,
|
|
207
|
-
},
|
|
208
|
-
},
|
|
209
|
-
},
|
|
210
|
-
})
|
|
211
|
-
```
|
|
212
|
-
|
|
213
|
-
In this example, the top-level idle setting is disabled for observations, while reflections opt into idle and provider-change activation.
|
|
214
|
-
|
|
215
|
-
### Buffer on idle
|
|
216
|
-
|
|
217
|
-
Set `observation.bufferOnIdle` to `true` to run background observation buffering when an agent turn ends and the agent becomes idle. This is useful for apps that want short turns to be observed without waiting for the next turn or the `messageTokens` threshold.
|
|
218
|
-
|
|
219
|
-
```typescript
|
|
220
|
-
import { Memory } from '@mastra/memory'
|
|
221
|
-
|
|
222
|
-
const memory = new Memory({
|
|
223
|
-
options: {
|
|
224
|
-
observationalMemory: {
|
|
225
|
-
model: 'openai/gpt-6-luna',
|
|
226
|
-
observation: {
|
|
227
|
-
bufferOnIdle: true,
|
|
228
|
-
},
|
|
229
|
-
},
|
|
230
|
-
},
|
|
231
|
-
})
|
|
79
|
+
console.log(second.text)
|
|
232
80
|
```
|
|
233
81
|
|
|
234
|
-
`
|
|
235
|
-
|
|
236
|
-
### Retries and failure policy
|
|
82
|
+
`resource` identifies the user or entity and `thread` identifies the conversation. Reuse both to continue the conversation. Nothing is observed in this short exchange. Once the thread's message history passes 30,000 tokens, OM starts replacing older messages with observations.
|
|
237
83
|
|
|
238
|
-
|
|
84
|
+
If your Mastra instance already has storage, you can leave `storage` out of `Memory` and it uses that.
|
|
239
85
|
|
|
240
|
-
|
|
241
|
-
- `failurePolicy`: what happens once retries are exhausted, either `'abort'` (default) or `'continue'`.
|
|
242
|
-
|
|
243
|
-
```typescript
|
|
244
|
-
import { Memory } from '@mastra/memory'
|
|
245
|
-
|
|
246
|
-
const memory = new Memory({
|
|
247
|
-
options: {
|
|
248
|
-
observationalMemory: {
|
|
249
|
-
observation: {
|
|
250
|
-
maxRetries: 8,
|
|
251
|
-
failurePolicy: 'continue',
|
|
252
|
-
},
|
|
253
|
-
reflection: {
|
|
254
|
-
maxRetries: 8,
|
|
255
|
-
failurePolicy: 'continue',
|
|
256
|
-
},
|
|
257
|
-
},
|
|
258
|
-
},
|
|
259
|
-
})
|
|
260
|
-
```
|
|
261
|
-
|
|
262
|
-
`maxRetries` governs OM's own retry ladder; the underlying model call is configured with no provider-level retries, so the option is the single retry knob for the stage.
|
|
263
|
-
|
|
264
|
-
With `failurePolicy: 'continue'`, Mastra retries as configured, reports the failure through the existing OM diagnostics, keeps the failed input pending for a later cycle, and lets the main agent turn continue. It doesn't advance observation boundaries or discard unobserved messages. A Reflector failure under `'continue'` leaves any already-persisted observations committed and defers reflection to the next threshold crossing.
|
|
265
|
-
|
|
266
|
-
A provider outage usually takes out both stages, so set the policy on both if you want the turn to survive one.
|
|
267
|
-
|
|
268
|
-
This policy applies only to Observer and Reflector model and provider failures when observation or reflection runs synchronously: at `blockAfter`, when async buffering is disabled, and in resource-scoped observation. In those paths, persistence, indexing, transform, locking, invariant, and explicit abort failures remain fatal. It doesn't prevent the underlying provider or network error, change `blockAfter`, or change attachment handling.
|
|
269
|
-
|
|
270
|
-
Background (async buffered) observation and reflection failures never stop the turn, whatever the policy. They're reported as `om_buffering_failed`, and the failed input stays pending. If it keeps growing, it reaches `blockAfter`, where synchronous observation applies `failurePolicy`.
|
|
271
|
-
|
|
272
|
-
> **Warning:** `'continue'` has no backstop for a sustained outage. Unobserved messages stay pending and keep accruing in the main agent's context. A long outage moves the failure from the memory layer to the model's context limit.
|
|
273
|
-
|
|
274
|
-
See [the API reference](https://mastra.ai/reference/memory/observational-memory) for the full configuration shape.
|
|
86
|
+
To watch OM work, open the **Memory** tab of the agent in [Studio](https://mastra.ai/docs/studio/overview). Progress bars show how close messages and observations are to their thresholds, and **Analyze observations** opens the observation log and its history.
|
|
275
87
|
|
|
276
88
|
## Benefits
|
|
277
89
|
|
|
278
|
-
- **
|
|
279
|
-
- **
|
|
280
|
-
- **
|
|
90
|
+
- **Long tasks stay in one thread**: The agent keeps working past its context limit without compacting and without losing earlier decisions.
|
|
91
|
+
- **Prompt caching**: Observations append to a stable prefix instead of being retrieved each turn, which lets the provider serve most of each request from its prompt cache. See [cost and latency](#cost-and-latency).
|
|
92
|
+
- **Smaller context**: Raw messages and tool results compress into a dense observation log, which lowers the cost and latency of every call.
|
|
93
|
+
- **Less context rot**: The agent reads what matters instead of stale tool output and noise, which keeps it on task over long sessions.
|
|
281
94
|
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
You don't remember every word of every conversation you've ever had. You observe what happened subconsciously, then your brain reflects, reorganizing, combining, and condensing into long-term memory. OM works the same way.
|
|
95
|
+
Mastra's own agents run on OM. [Mastra Code](https://code.mastra.ai/), a coding agent for the terminal, uses it so a session can run for days without compacting. [Mastra Factory](https://factory.mastra.ai/) runs its planning, implementation and review sessions on Mastra Code. Each agent keeps the context of a long task from start to finish.
|
|
285
96
|
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
- **Context rot**: the more raw message history an agent carries, the worse it performs.
|
|
289
|
-
- **Context waste**: most of that history contains tokens no longer needed to keep the agent on task.
|
|
97
|
+
## How it works
|
|
290
98
|
|
|
291
|
-
|
|
99
|
+
Every time an agent responds, it reads a context window holding its system prompt, recent messages and any injected context. The more raw history it carries, the worse it performs, and most of those tokens are no longer needed to stay on task. OM compresses that history.
|
|
292
100
|
|
|
293
101
|
### Observations
|
|
294
102
|
|
|
295
|
-
When
|
|
296
|
-
|
|
297
|
-
OM uses fast local token estimation for this thresholding work. Text is estimated with `tokenx`, while image parts use provider-aware heuristics so multimodal conversations still trigger observation at the right time. The same applies to image-like `file` parts when a transport normalizes an uploaded image as a file instead of an image part. For example, OpenAI image detail settings can materially change when OM decides to observe.
|
|
298
|
-
|
|
299
|
-
The Observer can also see attachments in the history it reviews. For readability, OM keeps placeholders such as `[Image #1: reference-board.png]` or `[File #1: floorplan.pdf]` in the transcript while forwarding the actual attachments beside the text. When possible, image-like `file` parts become image inputs for the Observer. Other attachments remain file parts and use normalized token counting. This applies to both normal thread observation and batched resource-scope observation.
|
|
300
|
-
|
|
301
|
-
### Extractors
|
|
302
|
-
|
|
303
|
-
Use extractors when you want OM to persist specific values alongside observations. Built-in values use the same extraction pipeline as custom values. They include **current task** and **suggested response**, along with **thread title**.
|
|
304
|
-
|
|
305
|
-
The following example extracts a compact user profile from observations:
|
|
306
|
-
|
|
307
|
-
```typescript
|
|
308
|
-
import { Agent } from '@mastra/core/agent'
|
|
309
|
-
import { Extractor, Memory } from '@mastra/memory'
|
|
310
|
-
import { z } from 'zod'
|
|
311
|
-
|
|
312
|
-
const memory = new Memory({
|
|
313
|
-
options: {
|
|
314
|
-
observationalMemory: {
|
|
315
|
-
model: 'openai/gpt-6-luna',
|
|
316
|
-
observation: {
|
|
317
|
-
extract: [
|
|
318
|
-
new Extractor({
|
|
319
|
-
name: 'User profile',
|
|
320
|
-
instructions: 'Extract stable user profile facts that should be remembered.',
|
|
321
|
-
schema: z.object({
|
|
322
|
-
preferredName: z.string().optional(),
|
|
323
|
-
timezone: z.string().optional(),
|
|
324
|
-
tools: z.array(z.string()).optional(),
|
|
325
|
-
}),
|
|
326
|
-
}),
|
|
327
|
-
],
|
|
328
|
-
},
|
|
329
|
-
},
|
|
330
|
-
},
|
|
331
|
-
})
|
|
332
|
-
|
|
333
|
-
export const agent = new Agent({
|
|
334
|
-
id: 'assistant',
|
|
335
|
-
name: 'assistant',
|
|
336
|
-
instructions: 'You are a helpful assistant.',
|
|
337
|
-
model: 'openai/gpt-6-luna',
|
|
338
|
-
memory,
|
|
339
|
-
})
|
|
340
|
-
```
|
|
341
|
-
|
|
342
|
-
Adding a `schema` makes the extractor run as a follow-up structured output request. Schema-less extractors are inline string extractors emitted directly in the Observer or Reflector response.
|
|
343
|
-
|
|
344
|
-
```typescript
|
|
345
|
-
new Extractor({
|
|
346
|
-
name: 'Mood',
|
|
347
|
-
instructions: 'Extract the user mood as a short phrase.',
|
|
348
|
-
})
|
|
349
|
-
```
|
|
350
|
-
|
|
351
|
-
By default, OM shows the last extracted value to the extractor on later runs. Set `includePreviousExtraction: false` when the Observer shouldn't see the previous value.
|
|
352
|
-
|
|
353
|
-
```typescript
|
|
354
|
-
new Extractor({
|
|
355
|
-
name: 'Latest blocker',
|
|
356
|
-
instructions: 'Extract any blockers the agent is running into.',
|
|
357
|
-
includePreviousExtraction: false,
|
|
358
|
-
})
|
|
359
|
-
```
|
|
360
|
-
|
|
361
|
-
Use runtime `instructions` or `schema` functions when an extractor needs runtime context, such as the active memory instance or request context:
|
|
362
|
-
|
|
363
|
-
```typescript
|
|
364
|
-
new Extractor({
|
|
365
|
-
name: 'Workspace summary',
|
|
366
|
-
instructions: ({ memory }) =>
|
|
367
|
-
memory ? 'Extract workspace facts for this memory instance.' : 'Extract workspace facts.',
|
|
368
|
-
})
|
|
369
|
-
```
|
|
370
|
-
|
|
371
|
-
#### Read extracted values from a stream
|
|
372
|
-
|
|
373
|
-
Extractor results are emitted when OM completes an observation or reflection. Read both completion data parts from the stream:
|
|
374
|
-
|
|
375
|
-
```typescript
|
|
376
|
-
const stream = await agent.stream('Remember that I prefer dark mode.')
|
|
377
|
-
|
|
378
|
-
for await (const chunk of stream.fullStream) {
|
|
379
|
-
if (chunk.type === 'data-om-observation-end' || chunk.type === 'data-om-buffering-end') {
|
|
380
|
-
const { operationType, extractedValues = {}, extractionFailures = [] } = chunk.data
|
|
381
|
-
|
|
382
|
-
for (const [slug, value] of Object.entries(extractedValues)) {
|
|
383
|
-
console.log(`${operationType} extractor ${slug}:`, value)
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
for (const failure of extractionFailures) {
|
|
387
|
-
console.error(`Extractor ${failure.slug} failed:`, failure.error)
|
|
388
|
-
}
|
|
389
|
-
}
|
|
390
|
-
}
|
|
391
|
-
```
|
|
392
|
-
|
|
393
|
-
`extractedValues` uses each extractor's slug as its key. Both result fields are optional, and a failed extractor doesn't remove values from successful extractors.
|
|
394
|
-
|
|
395
|
-
`data-om-observation-end` reports a synchronous completion. `data-om-buffering-end` reports completed background work. Its extractor metadata is persisted immediately, but the buffered content remains inactive until activation. Check `operationType` to determine whether the completed work was an observation or reflection.
|
|
396
|
-
|
|
397
|
-
See the [`data-om-observation-end`](https://mastra.ai/reference/memory/observational-memory) and [`data-om-buffering-end`](https://mastra.ai/reference/memory/observational-memory) reference tables for the complete payloads.
|
|
398
|
-
|
|
399
|
-
### Working memory updates
|
|
400
|
-
|
|
401
|
-
Use `observationalMemory.observation.manageWorkingMemory` to let the Observer manage working memory automatically. The main agent no longer needs to call the working memory tool while it handles the user request, so working memory updates don't depend on the agent remembering to make them.
|
|
402
|
-
|
|
403
|
-
This also keeps working memory prompt-cache friendly. Working memory normally lives in the system prompt, so updates can invalidate the prompt cache. OM-managed working memory defaults `workingMemory.useStateSignals` to `true`, which moves working memory into state signals instead.
|
|
404
|
-
|
|
405
|
-
```typescript
|
|
406
|
-
import { Memory } from '@mastra/memory'
|
|
407
|
-
|
|
408
|
-
const memory = new Memory({
|
|
409
|
-
options: {
|
|
410
|
-
workingMemory: {
|
|
411
|
-
enabled: true,
|
|
412
|
-
},
|
|
413
|
-
observationalMemory: {
|
|
414
|
-
enabled: true,
|
|
415
|
-
observation: {
|
|
416
|
-
manageWorkingMemory: true,
|
|
417
|
-
},
|
|
418
|
-
},
|
|
419
|
-
},
|
|
420
|
-
})
|
|
421
|
-
```
|
|
422
|
-
|
|
423
|
-
This setting adds `WorkingMemoryExtractor`, defaults `workingMemory.agentManaged` to `false`, and defaults `workingMemory.useStateSignals` to `true`. Set `workingMemory.agentManaged: true` if the main agent should still receive working memory tool and instruction injection.
|
|
424
|
-
|
|
425
|
-
Use `onExtracted` to normalize or react to custom extracted values before they're persisted:
|
|
426
|
-
|
|
427
|
-
```typescript
|
|
428
|
-
import { z } from 'zod'
|
|
429
|
-
|
|
430
|
-
new Extractor({
|
|
431
|
-
name: 'Project status',
|
|
432
|
-
instructions: 'Extract the current project status.',
|
|
433
|
-
schema: z.string(),
|
|
434
|
-
async onExtracted({ current, sendSignal }) {
|
|
435
|
-
await sendSignal?.({
|
|
436
|
-
type: 'user-message',
|
|
437
|
-
contents: `Project status extracted: ${current}`,
|
|
438
|
-
})
|
|
439
|
-
return current.trim().toLowerCase()
|
|
440
|
-
},
|
|
441
|
-
})
|
|
442
|
-
```
|
|
443
|
-
|
|
444
|
-
Extractor failures are reported in OM markers and don't block other successful extractor values. See [the API reference](https://mastra.ai/reference/memory/observational-memory) for the full `Extractor` shape.
|
|
445
|
-
|
|
446
|
-
If your Observer model is text-only or its API rejects multimodal input, set `observation.observeAttachments` to `false` to drop attachments before they reach the Observer. The readable placeholders (`[Image #1: ...]`, `[File #1: ...]`) are kept in the transcript so the Observer can still reason about what was shared without receiving the binary payload. The same filter applies to tool results that contain image or file parts:
|
|
447
|
-
|
|
448
|
-
```typescript
|
|
449
|
-
new Agent({
|
|
450
|
-
id: 'assistant',
|
|
451
|
-
name: 'assistant',
|
|
452
|
-
instructions: 'You are a helpful assistant.',
|
|
453
|
-
model: 'openai/gpt-6-luna',
|
|
454
|
-
memory: new Memory({
|
|
455
|
-
options: {
|
|
456
|
-
observationalMemory: {
|
|
457
|
-
observation: {
|
|
458
|
-
model: 'deepseek/deepseek-flash',
|
|
459
|
-
observeAttachments: false,
|
|
460
|
-
},
|
|
461
|
-
},
|
|
462
|
-
},
|
|
463
|
-
}),
|
|
464
|
-
})
|
|
465
|
-
```
|
|
466
|
-
|
|
467
|
-
You can also pass an allowlist of mimeType globs (for example `['image/*']`) to forward only the kinds the Observer can handle. Alternatively, set `observeAttachments: 'auto'` so Mastra consults the provider capabilities registry. It forwards attachments when the Observer model supports multimodal input and drops them otherwise. If capability data is unavailable for the model, the setting falls back to `true`.
|
|
468
|
-
|
|
469
|
-
Attachments that the agent recorded as unavailable, because they could no longer be downloaded, are never sent to the Observer. The Observer still sees their `[Image #1: ...]` or `[File #1: ...]` line. See [attachment download failures](https://mastra.ai/docs/agents/processors) for how Mastra records them.
|
|
103
|
+
When the thread's unobserved messages pass `observation.messageTokens` (default 30,000), the Observer writes observations: short, dated notes about what happened.
|
|
470
104
|
|
|
471
105
|
```md
|
|
472
106
|
Date: 2026-01-15
|
|
@@ -477,193 +111,94 @@ Date: 2026-01-15
|
|
|
477
111
|
- 🔴 12:15 User stated the app name is "Acme Dashboard"
|
|
478
112
|
```
|
|
479
113
|
|
|
480
|
-
The
|
|
114
|
+
The observed messages leave the context window and the observations take their place, typically 5 to 40 times smaller. A browser agent that sees 50,000 tokens per page snapshot ends up carrying a few hundred tokens about what was on the page and what it did.
|
|
481
115
|
|
|
482
|
-
|
|
116
|
+
During synchronous observation, the Observer also records a **current task** and a **suggested response**. These help the agent pick up where it left off. With `observation.threadTitle` enabled, it can suggest a new thread title when the topic changes.
|
|
483
117
|
|
|
484
|
-
|
|
118
|
+
The Observer sees attachments in the history it reviews. The transcript keeps placeholders such as `[Image #1: reference-board.png]`, and the attachments themselves are forwarded beside the text. See [choosing models](#choosing-models) for Observers that can't read attachments.
|
|
485
119
|
|
|
486
120
|
### Reflections
|
|
487
121
|
|
|
488
|
-
When observations
|
|
122
|
+
When observations pass `reflection.observationTokens` (default 40,000), the Reflector rewrites the whole log: it merges related items, condenses older ones more and keeps recent detail. Its output becomes the new log, and new observations append after it. The log stays around the reflection threshold however long the thread runs.
|
|
489
123
|
|
|
490
|
-
|
|
124
|
+
The agent's context then has three layers:
|
|
491
125
|
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
2. **Observations**: A log of what the Observer has seen
|
|
496
|
-
3. **Reflections**: Condensed observations when memory becomes too long
|
|
126
|
+
1. **Recent messages**: the exact conversation for the current task.
|
|
127
|
+
2. **Observations**: what the Observer has seen since the last reflection.
|
|
128
|
+
3. **Reflections**: the condensed log of everything before that.
|
|
497
129
|
|
|
498
130
|
### How context changes over time
|
|
499
131
|
|
|
500
|
-
With default settings, the context window
|
|
132
|
+
With the default settings, the context window grows and shrinks in a cycle:
|
|
501
133
|
|
|
502
134
|

|
|
503
135
|
|
|
504
|
-
1. **0
|
|
505
|
-
2. **
|
|
506
|
-
3. **Repeat**:
|
|
507
|
-
4. **Observations reach
|
|
508
|
-
|
|
509
|
-
In the normal buffered cycle, raw history oscillates between roughly 6k and 30k tokens. The observation log stays around 40k tokens, however long the conversation runs. These are activation thresholds rather than hard caps, so history can grow past the threshold whenever background buffering doesn't keep pace. Between the threshold and `blockAfter` (default `1.2`, \~36k tokens), buffering keeps running in the background and the next ready chunk activates without blocking the agent. At `blockAfter`, a synchronous observation runs if no buffered chunk activates. Reflection falls back to a synchronous run above its own `blockAfter` (\~48k tokens).
|
|
510
|
-
|
|
511
|
-
With [`shareTokenBudget`](https://mastra.ai/reference/memory/observational-memory) enabled, the two budgets pool together. While the observation log is small, message history can expand into the unused observation space (up to \~70k tokens with the defaults) before observation triggers. It then shrinks as observations accumulate.
|
|
136
|
+
1. **0 to 30,000 tokens**: message history grows. In the background, the Observer prepares observations about every 6,000 tokens (`observation.bufferTokens: 0.2`).
|
|
137
|
+
2. **30,000 reached**: the prepared observations activate. The observed messages leave the context and about 6,000 tokens of recent messages stay (`observation.bufferActivation: 0.8` keeps 20% of the threshold).
|
|
138
|
+
3. **Repeat**: history grows back toward 30,000 and shrinks again. Each cycle adds a little to the observation log.
|
|
139
|
+
4. **Observations reach 40,000**: the Reflector rewrites the log into a smaller one.
|
|
512
140
|
|
|
513
|
-
|
|
141
|
+
Thresholds mark when work starts. History can run past 30,000 tokens when background observation falls behind. At `observation.blockAfter` (default `1.2`, or 36,000 tokens) the agent waits for a synchronous observation. See [when buffering falls behind](https://mastra.ai/reference/memory/observational-memory).
|
|
514
142
|
|
|
515
|
-
|
|
143
|
+
Token counts are local `tokenx` estimates. The provider's own count is often higher, especially with attachments.
|
|
516
144
|
|
|
517
|
-
|
|
145
|
+
### Context-overflow recovery
|
|
518
146
|
|
|
519
|
-
|
|
147
|
+
A provider can reject a request for exceeding its context window before OM's estimate reaches the threshold. When that happens, OM activates any prepared observations, observes everything still pending, and retries the request once with the smaller context. This is on by default; set `observation.observeOnContextOverflow: false` to let the error reach your code instead.
|
|
520
148
|
|
|
521
|
-
|
|
522
|
-
const memory = new Memory({
|
|
523
|
-
options: {
|
|
524
|
-
observationalMemory: {
|
|
525
|
-
model: 'auto',
|
|
526
|
-
retrieval: true,
|
|
527
|
-
},
|
|
528
|
-
},
|
|
529
|
-
})
|
|
530
|
-
```
|
|
531
|
-
|
|
532
|
-
#### With semantic search
|
|
149
|
+
## Choosing models
|
|
533
150
|
|
|
534
|
-
|
|
151
|
+
The Observer and Reflector are model calls that run beside your agent. By default both use `model: 'auto'`, which resolves each time a role runs:
|
|
535
152
|
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
vector: myVectorStore,
|
|
540
|
-
embedder: myEmbedder,
|
|
541
|
-
options: {
|
|
542
|
-
observationalMemory: {
|
|
543
|
-
model: 'auto',
|
|
544
|
-
retrieval: { vector: true },
|
|
545
|
-
},
|
|
546
|
-
},
|
|
547
|
-
})
|
|
548
|
-
```
|
|
549
|
-
|
|
550
|
-
When vector search is configured, new observation groups are automatically indexed at buffer time and during synchronous observation (fire-and-forget, non-blocking). Semantic search returns observation-group matches with their raw source message ID ranges, so the recall tool can show the summarized memory alongside where it came from.
|
|
551
|
-
|
|
552
|
-
#### Restricting to the current thread
|
|
553
|
-
|
|
554
|
-
By default, the recall tool scope is `'resource'`, the agent can list threads and browse other threads, plus search across all conversations. Set `scope: 'thread'` to restrict the agent to only the current thread:
|
|
555
|
-
|
|
556
|
-
```typescript
|
|
557
|
-
const memory = new Memory({
|
|
558
|
-
options: {
|
|
559
|
-
observationalMemory: {
|
|
560
|
-
model: 'auto',
|
|
561
|
-
retrieval: { vector: true, scope: 'thread' },
|
|
562
|
-
},
|
|
563
|
-
},
|
|
564
|
-
})
|
|
565
|
-
```
|
|
153
|
+
1. `google/gemini-2.5-flash` when Google is usable: `GOOGLE_GENERATIVE_AI_API_KEY` is set, or your `canUseProvider` function returns `true` for `'google'`.
|
|
154
|
+
2. Otherwise, a low-cost model from the main model's provider, for example `anthropic/claude-haiku-4-5` for an Anthropic agent.
|
|
155
|
+
3. Otherwise, the main model itself.
|
|
566
156
|
|
|
567
|
-
|
|
157
|
+
`auto` reads the main model's `provider/model` ID. When that isn't known, such as a model created with a custom URL, API key or gateway, `auto` uses the main model itself, because a sibling model isn't known to share that route.
|
|
568
158
|
|
|
569
|
-
|
|
159
|
+
Set `model` to use one model for both roles:
|
|
570
160
|
|
|
571
161
|
```typescript
|
|
572
162
|
const memory = new Memory({
|
|
573
163
|
options: {
|
|
574
164
|
observationalMemory: {
|
|
575
|
-
model: '
|
|
576
|
-
retrieval: {
|
|
577
|
-
vector: true,
|
|
578
|
-
instructions: `
|
|
579
|
-
Prefer the current conversation when it already contains the answer.
|
|
580
|
-
For an initial scan, use a small limit with detail="low".
|
|
581
|
-
`,
|
|
582
|
-
},
|
|
165
|
+
model: 'deepseek/deepseek-flash',
|
|
583
166
|
},
|
|
584
167
|
},
|
|
585
168
|
})
|
|
586
169
|
```
|
|
587
170
|
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
#### What retrieval enables
|
|
591
|
-
|
|
592
|
-
With retrieval mode enabled, OM:
|
|
593
|
-
|
|
594
|
-
- Stores a `range` (e.g. `startId:endId`) on each observation group pointing to the messages it was derived from
|
|
595
|
-
|
|
596
|
-
- Keeps range metadata visible in the agent's context so the agent knows which observations map to which messages
|
|
597
|
-
|
|
598
|
-
- Registers a `recall` tool the agent can call to:
|
|
599
|
-
|
|
600
|
-
- Page through the raw messages behind any observation group range
|
|
601
|
-
- Search by semantic similarity (`mode: "search"` with a `query` string); requires `vector: true`
|
|
602
|
-
- List all threads (`mode: "threads"`), browse other threads (`threadId`), and search across all threads (default `scope: 'resource'`)
|
|
603
|
-
- When `scope: 'thread'`: restrict browsing and search to the current thread only
|
|
604
|
-
|
|
605
|
-
See the [recall tool reference](https://mastra.ai/reference/memory/observational-memory) for the full API (detail levels, part indexing, pagination, cross-thread browsing, and token limiting).
|
|
606
|
-
|
|
607
|
-
## Studio
|
|
171
|
+
Use a model with a large context window (128,000 tokens or more) that's fast enough to run in the background. Mastra has tested `google/gemini-2.5-flash`, `openai/gpt-6-luna`, `anthropic/claude-haiku-5-5` and `deepseek/deepseek-flash`.
|
|
608
172
|
|
|
609
|
-
To
|
|
173
|
+
To use a different model per role, set `observation.model` and `reflection.model` instead, and leave the top-level `model` out. Setting both throws. Some models keep so much detail that their reflections can stay above the threshold; in testing, `google/gemini-2.5-flash` did this. A common split uses a detail-preserving model as the Observer and one that condenses more readily, such as `deepseek/deepseek-flash`, as the Reflector. See [different models per agent](https://mastra.ai/reference/memory/observational-memory).
|
|
610
174
|
|
|
611
|
-
|
|
175
|
+
### Tune automatic selection
|
|
612
176
|
|
|
613
|
-
|
|
177
|
+
These `observationalMemory` options adjust what `auto` picks:
|
|
614
178
|
|
|
615
|
-
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
## Models
|
|
620
|
-
|
|
621
|
-
The Observer and Reflector run in the background. Any model that works with Mastra's [model routing](https://mastra.ai/models) (`provider/model`) can be used. When no model is set, the default is `model: 'auto'`.
|
|
622
|
-
|
|
623
|
-
Automatic selection uses `google/gemini-2.5-flash` when `GOOGLE_GENERATIVE_AI_API_KEY` is configured. Otherwise, it selects a low-cost model for the active main model's provider, then falls back to the active main model. Observer and Reflector resolve independently before each invocation.
|
|
624
|
-
|
|
625
|
-
Automatic selection reads the main model's `provider/model` ID. Models created from a plain model string carry that ID, and a dynamic model function can label a custom model by returning `{ model, id }`. When the ID is unknown, such as a model with a custom URL, API key, headers, or gateway, automatic selection reuses the main model itself because a sibling model isn't known to share that route. Pass a concrete model ID to the role to override either behavior.
|
|
626
|
-
|
|
627
|
-
Use `autoModels` to change the model picked for a provider, and `resolveModel` to create the picked model with your own credentials or routing:
|
|
179
|
+
- `autoModels`: replace the low-cost pick for a provider, for example `{ openai: 'openai/gpt-6-luna' }`.
|
|
180
|
+
- `canUseProvider`: tell `auto` whether the current request can use a provider, when credentials are per tenant or per request rather than in the server's environment. It receives the provider ID and `{ requestContext }`.
|
|
181
|
+
- `resolveModel`: create the picked model yourself, with your own credentials or routing. It receives a concrete model ID, never `'auto'`.
|
|
628
182
|
|
|
629
183
|
```typescript
|
|
630
184
|
const memory = new Memory({
|
|
631
185
|
options: {
|
|
632
186
|
observationalMemory: {
|
|
633
187
|
autoModels: { openai: 'openai/gpt-6-luna' },
|
|
188
|
+
canUseProvider: (provider, { requestContext }) => hasCredentials(provider, requestContext),
|
|
634
189
|
resolveModel: (modelId, { requestContext }) => createRoutedModel(modelId, requestContext),
|
|
635
190
|
},
|
|
636
191
|
},
|
|
637
192
|
})
|
|
638
193
|
```
|
|
639
194
|
|
|
640
|
-
`resolveAutoModelId(mainModelId, { autoModels })` from `@mastra/memory` returns the model
|
|
641
|
-
|
|
642
|
-
Mastra recommends using a model that has a large context window (128K+ tokens) and is fast enough to run in the background without slowing down your actions.
|
|
643
|
-
|
|
644
|
-
To pin a model instead, set a concrete model ID. We've also successfully tested `openai/gpt-6-luna`, `anthropic/claude-haiku-5-5`, and `deepseek/deepseek-flash`.
|
|
645
|
-
|
|
646
|
-
```typescript
|
|
647
|
-
const memory = new Memory({
|
|
648
|
-
options: {
|
|
649
|
-
observationalMemory: {
|
|
650
|
-
model: 'deepseek/deepseek-flash',
|
|
651
|
-
},
|
|
652
|
-
},
|
|
653
|
-
})
|
|
654
|
-
```
|
|
655
|
-
|
|
656
|
-
See [model configuration](https://mastra.ai/reference/memory/observational-memory) for using different models per agent.
|
|
657
|
-
|
|
658
|
-
> **Note:** Some models preserve detail in long output unusually well. In testing, `google/gemini-2.5-flash` did this. Other models may behave differently. With such a model, the Reflector can produce reflections that stay above the configured `reflection.observationTokens` threshold even after the maximum compression retry. When this happens, the Reflector returns the smallest non-degenerate candidate produced during retries so the loop terminates instead of running forever.
|
|
659
|
-
>
|
|
660
|
-
> If you'd rather have more aggressive compression on the Reflector, pick a model that condenses more readily, such as `deepseek/deepseek-flash`. You can use a detail-preserving model for the Observer and a condensing one for the Reflector. See [different models per agent](https://mastra.ai/reference/memory/observational-memory).
|
|
195
|
+
`resolveAutoModelId(mainModelId, { autoModels })` from `@mastra/memory` returns the model `auto` would pick, for showing the effective model in a settings UI.
|
|
661
196
|
|
|
662
|
-
### Token-tiered
|
|
197
|
+
### Token-tiered models
|
|
663
198
|
|
|
664
199
|
**Added in:** `@mastra/memory@1.10.0`
|
|
665
200
|
|
|
666
|
-
|
|
201
|
+
`ModelByInputTokens` picks a model by the size of each Observer or Reflector call:
|
|
667
202
|
|
|
668
203
|
```typescript
|
|
669
204
|
import { Memory, ModelByInputTokens } from '@mastra/memory'
|
|
@@ -674,7 +209,6 @@ const memory = new Memory({
|
|
|
674
209
|
observation: {
|
|
675
210
|
model: new ModelByInputTokens({
|
|
676
211
|
upTo: {
|
|
677
|
-
// Faster, cheaper models for smaller inputs; stronger models for larger contexts
|
|
678
212
|
5_000: 'openrouter/mistralai/ministral-8b-2512',
|
|
679
213
|
20_000: 'openrouter/mistralai/mistral-small-2603',
|
|
680
214
|
40_000: 'openai/gpt-6-luna',
|
|
@@ -695,360 +229,266 @@ const memory = new Memory({
|
|
|
695
229
|
})
|
|
696
230
|
```
|
|
697
231
|
|
|
698
|
-
|
|
232
|
+
Each tier needs a concrete model ID, not `'auto'`. Each `upTo` key is an inclusive upper bound. A call larger than the biggest key throws, so make the last tier cover the largest input you expect.
|
|
699
233
|
|
|
700
|
-
|
|
234
|
+
### Attachments and text-only Observers
|
|
701
235
|
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
### Thread scope (default)
|
|
236
|
+
By default the Observer receives images and PDFs (`observation.observeAttachments: ['image/*', 'application/pdf']`). Other attachments are left out, and their placeholders stay in the transcript. Change it when your Observer model handles more or less:
|
|
705
237
|
|
|
706
|
-
|
|
238
|
+
- `false`: send no attachments. Use this for a text-only Observer.
|
|
239
|
+
- `true`: send every attachment.
|
|
240
|
+
- A list of MIME types such as `['image/*']`: send only matching attachments. Matching is case-insensitive and `*` matches any subtype.
|
|
241
|
+
- `'auto'`: send attachments when the provider registry says the Observer model accepts multimodal input. When it has no data for the model, everything is sent.
|
|
707
242
|
|
|
708
243
|
```typescript
|
|
709
244
|
const memory = new Memory({
|
|
710
245
|
options: {
|
|
711
246
|
observationalMemory: {
|
|
712
|
-
|
|
713
|
-
|
|
247
|
+
observation: {
|
|
248
|
+
model: 'deepseek/deepseek-flash',
|
|
249
|
+
observeAttachments: false,
|
|
250
|
+
},
|
|
714
251
|
},
|
|
715
252
|
},
|
|
716
253
|
})
|
|
717
254
|
```
|
|
718
255
|
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
### Resource scope (deprecated)
|
|
722
|
-
|
|
723
|
-
> **Deprecated:** `scope: 'resource'` is deprecated and will be removed in a future release. Mastra logs a warning the first time Observational Memory is created with resource scope. Remove the `scope` option to use the default thread scope, and use the [alternatives below](#cross-thread-continuity-without-resource-scope) for cross-conversation continuity.
|
|
724
|
-
|
|
725
|
-
In resource scope, observations are shared across all threads for a resource (typically a user). Resource scope works much worse than thread scope for prompt caching and for the agent's understanding of the conversation:
|
|
726
|
-
|
|
727
|
-
- **Prompt caching:** Observations from every thread share one record. When any thread is observed, the observation context changes for all other threads, which invalidates their cached prompt prefix.
|
|
728
|
-
- **Agent understanding:** Each thread sees a mix of observations from every thread for the resource. Every new thread starts with context from earlier threads, and the agent may continue work that another thread started but didn't finish.
|
|
729
|
-
- **Performance:** Unobserved messages across _all_ threads are processed together, which is slow for users with many existing threads.
|
|
256
|
+
The same filter applies to images and files inside tool results. Attachments the agent recorded as unavailable, because they could no longer be downloaded, are never sent. See [attachment download failures](https://mastra.ai/docs/agents/processors).
|
|
730
257
|
|
|
731
|
-
|
|
258
|
+
## Cost and latency
|
|
732
259
|
|
|
733
|
-
|
|
260
|
+
Each observation and reflection is a model call. With the defaults, a thread costs one Observer call for roughly every 6,000 tokens of new messages, and one Reflector call each time the log reaches 40,000 tokens. In return, every main-agent call reads a context of at most a few tens of thousands of tokens instead of the whole thread. The observation prefix changes rarely, so prompt caching keeps working: users generally see 97 to 99% prompt cache hit rates with OM.
|
|
734
261
|
|
|
735
|
-
|
|
262
|
+
The Observer runs ahead in the background (async buffering), so the agent doesn't stop to wait for it. These settings control the timing:
|
|
736
263
|
|
|
737
|
-
|
|
264
|
+
| Setting | Default | What it controls |
|
|
265
|
+
| ------------------------------ | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
266
|
+
| `observation.bufferTokens` | `0.2` | How often the Observer runs in the background, as a fraction of `messageTokens` (`0.2` is every 6,000 tokens at the default threshold), or an absolute token count such as `5000`. `false` turns buffering off. |
|
|
267
|
+
| `observation.bufferActivation` | `0.8` | How much of the message window clears when observations activate. `0.8` keeps 20% of `messageTokens`. Lower values keep more recent messages. |
|
|
268
|
+
| `observation.blockAfter` | `1.2` | When the agent waits for a synchronous observation because buffering fell behind, as a multiple of `messageTokens` (`1.2` is 36,000 tokens), or an absolute count of 100 or more. `1` observes synchronously at `messageTokens`. |
|
|
738
269
|
|
|
739
|
-
|
|
740
|
-
- [Resource-scoped working memory](https://mastra.ai/docs/memory/working-memory): Stores small, durable facts about the user that every thread can read.
|
|
270
|
+
To change when OM observes and reflects, set the thresholds:
|
|
741
271
|
|
|
742
272
|
```typescript
|
|
743
273
|
const memory = new Memory({
|
|
744
274
|
options: {
|
|
745
275
|
observationalMemory: {
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
276
|
+
observation: {
|
|
277
|
+
messageTokens: 30_000,
|
|
278
|
+
},
|
|
279
|
+
reflection: {
|
|
280
|
+
observationTokens: 40_000,
|
|
281
|
+
},
|
|
752
282
|
},
|
|
753
283
|
},
|
|
754
284
|
})
|
|
755
285
|
```
|
|
756
286
|
|
|
757
|
-
|
|
287
|
+
### Long runs of tool calls
|
|
758
288
|
|
|
759
|
-
|
|
289
|
+
Agents that run long chains of tool calls, such as coding and browser agents, re-send the same growing prefix on every step, and the provider serves most of it from the prompt cache. For these agents, raise the observation threshold well above the default, for example to 60,000 to 80,000 tokens, so OM compresses less often and more of each run stays cached:
|
|
760
290
|
|
|
761
291
|
```typescript
|
|
762
292
|
const memory = new Memory({
|
|
763
293
|
options: {
|
|
764
294
|
observationalMemory: {
|
|
765
|
-
model: 'auto',
|
|
766
295
|
observation: {
|
|
767
|
-
|
|
768
|
-
messageTokens: 30_000,
|
|
769
|
-
},
|
|
770
|
-
reflection: {
|
|
771
|
-
// when to run the Reflector (default: 40,000)
|
|
772
|
-
observationTokens: 40_000,
|
|
296
|
+
messageTokens: 70_000,
|
|
773
297
|
},
|
|
774
|
-
// let message history borrow from observation budget
|
|
775
|
-
// requires bufferTokens: false (temporary limitation)
|
|
776
|
-
shareTokenBudget: false,
|
|
777
298
|
},
|
|
778
299
|
},
|
|
779
300
|
})
|
|
780
301
|
```
|
|
781
302
|
|
|
782
|
-
|
|
303
|
+
Keep the threshold within the main model's context window. `bufferTokens`, `bufferActivation` and `blockAfter` are fractions of `messageTokens` by default, so they scale with it.
|
|
783
304
|
|
|
784
|
-
|
|
305
|
+
### Activate when the prompt cache expires
|
|
785
306
|
|
|
786
|
-
|
|
787
|
-
- For string-only message content (without parts), OM uses a message-level metadata fallback cache.
|
|
788
|
-
- Message and conversation overhead are still recalculated on every pass. The cache only stores payload estimates, so counting semantics stay the same.
|
|
789
|
-
- `data-*` and `reasoning` parts are still skipped and aren't cached.
|
|
790
|
-
|
|
791
|
-
### Caller-supplied token estimates for file parts
|
|
792
|
-
|
|
793
|
-
You can attach a token estimate directly to an `image` or `file` part using `providerMetadata.mastra.tokenEstimate`. The Token Counter honors this value verbatim and skips its own estimator:
|
|
307
|
+
Once the prompt cache expires, the next request pays full price for the whole context anyway. `activateAfterIdle` makes OM activate its prepared observations when a thread has been idle that long, so the request after a pause sends a smaller, compressed context. It isn't set by default. Set it to `'auto'` to use the active provider's prompt cache TTL (for example 5 minutes for Anthropic, 1 hour for DeepSeek):
|
|
794
308
|
|
|
795
309
|
```typescript
|
|
796
|
-
const
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
filename: 'large-report.pdf',
|
|
801
|
-
providerMetadata: {
|
|
802
|
-
mastra: {
|
|
803
|
-
tokenEstimate: {
|
|
804
|
-
v: 0,
|
|
805
|
-
source: 'client',
|
|
806
|
-
key: 'client',
|
|
807
|
-
tokens: 100_000,
|
|
808
|
-
},
|
|
310
|
+
const memory = new Memory({
|
|
311
|
+
options: {
|
|
312
|
+
observationalMemory: {
|
|
313
|
+
activateAfterIdle: 'auto',
|
|
809
314
|
},
|
|
810
315
|
},
|
|
811
|
-
}
|
|
316
|
+
})
|
|
812
317
|
```
|
|
813
318
|
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
- `v`: cache schema version. Set to `0`. Caller-supplied entries are exempt from the framework's version check, so the value isn't read.
|
|
817
|
-
- `source`: cache lineage marker. Must be `'client'`. This is what tells the Token Counter the entry is authoritative and should be honored verbatim instead of being recomputed or overwritten.
|
|
818
|
-
- `key`: content fingerprint slot. Set to `'client'`. Framework entries use a content hash here so they invalidate when the payload changes. The `'client'` sentinel keeps caller estimates stable across writes.
|
|
819
|
-
- `tokens`: the token count to use. Must be a finite non-negative number.
|
|
820
|
-
|
|
821
|
-
Additional notes:
|
|
319
|
+
See [early activation](https://mastra.ai/reference/memory/observational-memory) for fixed durations, per-provider values and activating when the provider changes.
|
|
822
320
|
|
|
823
|
-
|
|
321
|
+
### Synchronous observation
|
|
824
322
|
|
|
825
|
-
|
|
323
|
+
To observe synchronously instead, set `observation.bufferTokens: false`. That turns off background buffering for both observations and reflections, and the agent pauses while each one runs.
|
|
826
324
|
|
|
827
|
-
|
|
325
|
+
`shareTokenBudget: true` lets message history borrow the unused part of the observation budget, so up to about 70,000 tokens of messages stay before observation starts while the log is small. It requires `observation.bufferTokens: false`. See [shared token budget](https://mastra.ai/reference/memory/observational-memory).
|
|
828
326
|
|
|
829
|
-
|
|
327
|
+
## Threads and cross-thread memory
|
|
830
328
|
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
When message tokens reach the `messageTokens` threshold, buffered chunks activate: their observations move into the active observation log, and the corresponding raw messages are removed from the context window. The agent never pauses.
|
|
834
|
-
|
|
835
|
-
Async buffered Observer calls don't generate continuation hints because delayed hints can be stale by activation time. When buffered chunks activate, any previously stored suggested response and current task are cleared. The main agent receives the compressed observations without those hints.
|
|
836
|
-
|
|
837
|
-
When message production outpaces the Observer, history can pass `messageTokens` before a buffered chunk is ready. Between `messageTokens` and `blockAfter`, Mastra keeps buffering in the background and activates the chunk on a later step, so the agent doesn't wait on the Observer. A synchronous observation runs if pending tokens still reach `blockAfter` after buffered activation, for example when a large tool result leaves an uncovered tail. Above `blockAfter`, activation may also overshoot the retention target instead of using fewer chunks. Buffered activation usually preserves a minimum remaining context (the smaller of \~1k tokens or the configured retention floor), but a single buffered chunk that covers the whole pending window still activates and can leave less.
|
|
329
|
+
### Thread scope (default)
|
|
838
330
|
|
|
839
|
-
|
|
331
|
+
Each thread has its own observations. Every call needs a thread: without one, OM throws `OBSERVATIONAL_MEMORY_THREAD_ID_REQUIRED`, so that unrelated threads never share one observation record.
|
|
840
332
|
|
|
841
|
-
|
|
333
|
+
> **Warning:** When a client application calls your agent, send only the new message instead of the full conversation. OM already loads the thread's history from storage. See [message history](https://mastra.ai/docs/memory/message-history) for how Mastra handles echoed history and when to use `retainFullInput`.
|
|
842
334
|
|
|
843
|
-
|
|
335
|
+
OM remembers within a thread. To let the agent reach a user's other threads, turn on [retrieval mode](#retrieval-mode), which gives it a `recall` tool for the raw messages behind observations and for other threads of the same resource.
|
|
844
336
|
|
|
845
|
-
|
|
846
|
-
| ------------------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
847
|
-
| `observation.bufferTokens` | `0.2` | How often to buffer. `0.2` means every 20% of `messageTokens`. With the default 30k threshold, that's roughly every 6k tokens. Can also be an absolute token count (e.g. `5000`). |
|
|
848
|
-
| `observation.bufferActivation` | `0.8` | How aggressively to clear the message window on activation. `0.8` means remove enough messages to keep only 20% of `messageTokens` remaining. Lower values keep more message history. |
|
|
849
|
-
| `observation.blockAfter` | `1.2` | Safety net if buffering can't keep up. Values from 1 up to (but not including) 100 multiply `messageTokens`. For example, `1.2` creates a threshold of 36k tokens (1.2 × 30k). Below it, only background buffering and activation run. Observation runs synchronously if pending tokens still reach it after buffered activation. Activation may also overshoot the retention target. Values of 100 or more are absolute token counts (e.g. `50_000`) and must be greater than `messageTokens`. Set `1` to observe synchronously at `messageTokens`. |
|
|
850
|
-
| `activateAfterIdle` | none | Forces buffered observations to activate after a period of inactivity, even before `observation.messageTokens` is reached. Accepts a numeric millisecond value such as `300_000`, duration strings like `"5m"` or `"1hr"`, `"auto"` for a provider-aware prompt cache TTL, or an object of per-provider TTLs such as `{ default: 'auto', anthropic: '1h' }`. |
|
|
851
|
-
| `activateOnProviderChange` | `false` | Forces buffered observations to activate when the next step uses a different `provider/model` than the one that produced the latest assistant step. Use this when switching providers or models would invalidate prompt cache reuse. |
|
|
852
|
-
| `reflection.bufferActivation` | `0.5` | When to start background reflection. `0.5` means reflection begins when observations reach 50% of the `observationTokens` threshold. |
|
|
853
|
-
| `reflection.activateAfterIdle` | none | Opts buffered reflections into idle activation. Reflections don't inherit top-level `activateAfterIdle`. |
|
|
854
|
-
| `reflection.activateOnProviderChange` | `false` | Opts buffered reflections into provider-change activation. Reflections don't inherit top-level `activateOnProviderChange`. |
|
|
855
|
-
| `reflection.blockAfter` | `1.2` | Safety threshold for reflection. Same value format as observation (absolute values must be greater than `observationTokens`), but above it reflection runs synchronously when no buffered reflection is ready to activate. |
|
|
337
|
+
### Retrieval mode
|
|
856
338
|
|
|
857
|
-
|
|
339
|
+
Observations drop the original wording. With retrieval mode, each observation group stays linked to the messages it came from, and the agent gets a `recall` tool to read them back, including exact wording and tool output.
|
|
858
340
|
|
|
859
|
-
|
|
341
|
+
`retrieval: true` lets the agent browse raw messages, list the resource's threads and read other threads. No vector store is needed.
|
|
860
342
|
|
|
861
|
-
|
|
862
|
-
| ------------------------------------------------------------------------------------------------------ | --------- |
|
|
863
|
-
| Anthropic, OpenRouter, unknown providers, xAI | 5 minutes |
|
|
864
|
-
| DeepSeek | 1 hour |
|
|
865
|
-
| Google Gemini | 24 hours |
|
|
866
|
-
| Groq | 2 hours |
|
|
867
|
-
| OpenAI with `providerOptions.openai.promptCacheRetention: "24h"` | 1 hour |
|
|
868
|
-
| OpenAI with `providerOptions.openai.promptCacheRetention: "in_memory"` | 5 minutes |
|
|
869
|
-
| OpenAI `gpt-4*`, `gpt-5`, `gpt-5-*`, and `gpt-5.1` through `gpt-5.4` (including `-` suffixed variants) | 5 minutes |
|
|
870
|
-
| Other OpenAI models | 1 hour |
|
|
343
|
+
`retrieval: { vector: true }` adds semantic search over observation groups, using the vector store and embedder configured on `Memory`. With a vector store that generates embeddings itself, leave the `embedder` out. See [server-side embeddings](https://mastra.ai/docs/memory/semantic-recall). New observation groups are indexed in the background as they're created.
|
|
871
344
|
|
|
872
345
|
```typescript
|
|
873
346
|
const memory = new Memory({
|
|
347
|
+
storage,
|
|
348
|
+
vector: myVectorStore,
|
|
349
|
+
embedder: myEmbedder,
|
|
874
350
|
options: {
|
|
875
351
|
observationalMemory: {
|
|
876
|
-
|
|
877
|
-
activateAfterIdle: 'auto',
|
|
878
|
-
activateOnProviderChange: true,
|
|
352
|
+
retrieval: { vector: true },
|
|
879
353
|
},
|
|
880
354
|
},
|
|
881
355
|
})
|
|
882
356
|
```
|
|
883
357
|
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
Changing models or providers mid-thread will invalidate the prompt cache. If your agent can switch between providers or models mid-thread, `activateOnProviderChange: true` forces buffered observations to activate before the new provider runs. That avoids sending a large raw window to a provider that can't reuse the previous prompt cache.
|
|
358
|
+
The recall tool's scope is `'resource'` by default, so it can reach every thread of the resource. Set `retrieval: { scope: 'thread' }` to limit it to the current thread. Use `retrieval.instructions` to add app-specific guidance after the built-in recall instructions, for example "Prefer the current conversation when it already contains the answer."
|
|
887
359
|
|
|
888
|
-
|
|
360
|
+
See the [recall tool reference](https://mastra.ai/reference/memory/observational-memory) for its modes, detail levels and pagination.
|
|
889
361
|
|
|
890
|
-
|
|
362
|
+
### Resource scope (deprecated)
|
|
891
363
|
|
|
892
|
-
|
|
893
|
-
const memory = new Memory({
|
|
894
|
-
options: {
|
|
895
|
-
observationalMemory: {
|
|
896
|
-
model: 'auto',
|
|
897
|
-
activateAfterIdle: { default: 'auto', anthropic: '1h' },
|
|
898
|
-
},
|
|
899
|
-
},
|
|
900
|
-
})
|
|
901
|
-
```
|
|
364
|
+
> **Deprecated:** `scope: 'resource'` is deprecated and will be removed in a future release. Mastra logs a warning the first time OM is created with resource scope. Remove the `scope` option to use thread scope, and use [retrieval mode](#retrieval-mode) for cross-thread continuity. [Knowledge](https://mastra.ai/docs/knowledge/overview), now in alpha, gives agents shared information across threads and is planned to replace resource scope.
|
|
902
365
|
|
|
903
|
-
|
|
366
|
+
Resource scope shares one observation record across all of a resource's threads. It works much worse than thread scope:
|
|
904
367
|
|
|
905
|
-
|
|
368
|
+
- **Prompt caching**: observing any thread changes the context of every other thread, which breaks their cached prefixes.
|
|
369
|
+
- **Agent understanding**: each thread sees observations from every other thread, and the agent may continue work that another thread started.
|
|
370
|
+
- **Performance**: unobserved messages from all threads are processed together, which is slow for users with many threads. Resource scope also turns off async buffering.
|
|
906
371
|
|
|
907
|
-
|
|
908
|
-
- Each value accepts the same forms as a single TTL: milliseconds, a duration string, `"auto"`, or `false` to turn off idle activation for that provider.
|
|
909
|
-
- `default` applies to every provider without its own key. Without `default`, those providers don't idle-activate.
|
|
910
|
-
- `observation.activateAfterIdle` and `reflection.activateAfterIdle` accept the same object. An `observation.activateAfterIdle` object replaces the top-level value and isn't merged with it.
|
|
372
|
+
Switching to thread scope doesn't migrate resource-scoped observations. Each thread uses its own thread-scoped record if it has one, or starts empty, and messages already observed under resource scope aren't observed again.
|
|
911
373
|
|
|
912
|
-
|
|
374
|
+
## Extractors
|
|
913
375
|
|
|
914
|
-
|
|
376
|
+
Extractors persist specific values alongside observations. The built-in current task, suggested response and thread title use the same pipeline. This example extracts a small user profile:
|
|
915
377
|
|
|
916
378
|
```typescript
|
|
379
|
+
import { Agent } from '@mastra/core/agent'
|
|
380
|
+
import { Extractor, Memory } from '@mastra/memory'
|
|
381
|
+
import { z } from 'zod'
|
|
382
|
+
|
|
917
383
|
const memory = new Memory({
|
|
918
384
|
options: {
|
|
919
385
|
observationalMemory: {
|
|
920
|
-
model: 'auto',
|
|
921
386
|
observation: {
|
|
922
|
-
|
|
387
|
+
extract: [
|
|
388
|
+
new Extractor({
|
|
389
|
+
name: 'User profile',
|
|
390
|
+
instructions: 'Extract stable user profile facts that should be remembered.',
|
|
391
|
+
schema: z.object({
|
|
392
|
+
preferredName: z.string().optional(),
|
|
393
|
+
timezone: z.string().optional(),
|
|
394
|
+
tools: z.array(z.string()).optional(),
|
|
395
|
+
}),
|
|
396
|
+
}),
|
|
397
|
+
],
|
|
923
398
|
},
|
|
924
399
|
},
|
|
925
400
|
},
|
|
926
401
|
})
|
|
927
|
-
```
|
|
928
402
|
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
403
|
+
export const assistant = new Agent({
|
|
404
|
+
id: 'assistant',
|
|
405
|
+
name: 'Assistant',
|
|
406
|
+
instructions: 'You are a helpful assistant.',
|
|
407
|
+
model: 'openai/gpt-6-luna',
|
|
408
|
+
memory,
|
|
409
|
+
})
|
|
410
|
+
```
|
|
932
411
|
|
|
933
|
-
|
|
412
|
+
An extractor with a `schema` runs as a follow-up structured-output request. Without a schema it's an inline string extractor, emitted directly in the Observer or Reflector response:
|
|
934
413
|
|
|
935
|
-
|
|
414
|
+
```typescript
|
|
415
|
+
new Extractor({
|
|
416
|
+
name: 'Mood',
|
|
417
|
+
instructions: 'Extract the user mood as a short phrase.',
|
|
418
|
+
})
|
|
419
|
+
```
|
|
936
420
|
|
|
937
|
-
|
|
421
|
+
By default the extractor sees its last value on later runs. Set `includePreviousExtraction: false` to hide it:
|
|
938
422
|
|
|
939
423
|
```typescript
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
observation: {
|
|
945
|
-
previousObserverTokens: 10_000, // keep only ~10k tokens of recent observations
|
|
946
|
-
},
|
|
947
|
-
},
|
|
948
|
-
},
|
|
424
|
+
new Extractor({
|
|
425
|
+
name: 'Latest blocker',
|
|
426
|
+
instructions: 'Extract any blockers the agent is running into.',
|
|
427
|
+
includePreviousExtraction: false,
|
|
949
428
|
})
|
|
950
429
|
```
|
|
951
430
|
|
|
952
|
-
|
|
953
|
-
- `previousObserverTokens: 2000` → keeps \~2k tokens of recent observations.
|
|
954
|
-
- `previousObserverTokens: 0` → omit previous observations completely.
|
|
431
|
+
`instructions` and `schema` can be functions when they depend on runtime context, such as the memory instance or request context:
|
|
955
432
|
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
433
|
+
```typescript
|
|
434
|
+
new Extractor({
|
|
435
|
+
name: 'Workspace summary',
|
|
436
|
+
instructions: ({ memory }) =>
|
|
437
|
+
memory ? 'Extract workspace facts for this memory instance.' : 'Extract workspace facts.',
|
|
438
|
+
})
|
|
439
|
+
```
|
|
959
440
|
|
|
960
|
-
|
|
961
|
-
- **Transform hooks** (`beforeObservation`, `afterObservation`, `beforeReflection`, `afterReflection`) intercept the data flowing through a cycle. Return `void` to pass the input through unchanged, or return a replacement to change what the Observer/Reflector sees or what gets persisted.
|
|
441
|
+
Use `onExtracted` to normalize a value before it's persisted:
|
|
962
442
|
|
|
963
443
|
```typescript
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
// Drop or redact messages before the Observer sees them.
|
|
970
|
-
beforeObservation: ({ messages }) => ({
|
|
971
|
-
messages: messages.filter(m => !isSensitive(m)),
|
|
972
|
-
}),
|
|
973
|
-
// Rewrite observations before they are persisted.
|
|
974
|
-
afterObservation: ({ observations, threadId }) => ({
|
|
975
|
-
observations: redact(observations),
|
|
976
|
-
}),
|
|
977
|
-
// Rewrite the text the Reflector condenses, or its output.
|
|
978
|
-
beforeReflection: ({ observations }) => ({
|
|
979
|
-
observations: stripInternalNotes(observations),
|
|
980
|
-
}),
|
|
981
|
-
afterReflection: async ({ observations, resourceId }) => {
|
|
982
|
-
await syncToExternalStore(resourceId, observations)
|
|
983
|
-
},
|
|
984
|
-
},
|
|
985
|
-
},
|
|
986
|
-
},
|
|
444
|
+
new Extractor({
|
|
445
|
+
name: 'Project status',
|
|
446
|
+
instructions: 'Extract the current project status.',
|
|
447
|
+
schema: z.string(),
|
|
448
|
+
onExtracted: ({ current }) => current.trim().toLowerCase(),
|
|
987
449
|
})
|
|
988
450
|
```
|
|
989
451
|
|
|
990
|
-
|
|
452
|
+
`onExtracted` also receives `previous` and `sendSignal`, so it can tell the agent when a value changes. The hook runs on every extraction, so compare `previous` with `current` before sending a signal; otherwise each observation sends another one.
|
|
991
453
|
|
|
992
|
-
|
|
454
|
+
A failed extractor is reported in OM markers and doesn't drop values from extractors that succeeded. See the [Extractor API](https://mastra.ai/reference/memory/observational-memory) for the full shape.
|
|
993
455
|
|
|
994
|
-
|
|
456
|
+
### Read extracted values from a stream
|
|
995
457
|
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
Agent skills are injected into the agent as tools (`skill`, `skill_search`, `skill_read`). Their results contain the skill's full instructions or file contents, so without redaction the Observer re-observes that text every time a skill is used. `skillResultRedactor()` is a ready-made `beforeObservation` hook that replaces those results with a placeholder and leaves everything else in place. The tool call survives, so the Observer still records which skill was used and what it was called with.
|
|
458
|
+
Extractor results arrive when OM completes an observation or reflection. Read both completion data parts from the stream:
|
|
999
459
|
|
|
1000
460
|
```typescript
|
|
1001
|
-
import {
|
|
1002
|
-
import { skillResultRedactor } from '@mastra/memory/hooks'
|
|
461
|
+
import { assistant } from './mastra/agents/assistant'
|
|
1003
462
|
|
|
1004
|
-
const
|
|
1005
|
-
|
|
1006
|
-
observationalMemory: {
|
|
1007
|
-
model: 'google/gemini-3.8-flash',
|
|
1008
|
-
hooks: {
|
|
1009
|
-
beforeObservation: skillResultRedactor(),
|
|
1010
|
-
},
|
|
1011
|
-
},
|
|
1012
|
-
},
|
|
463
|
+
const stream = await assistant.stream('Remember that I prefer dark mode.', {
|
|
464
|
+
memory: { resource: 'user-123', thread: 'conversation-123' },
|
|
1013
465
|
})
|
|
1014
|
-
```
|
|
1015
466
|
|
|
1016
|
-
|
|
467
|
+
for await (const chunk of stream.fullStream) {
|
|
468
|
+
if (chunk.type === 'data-om-observation-end' || chunk.type === 'data-om-buffering-end') {
|
|
469
|
+
const { operationType, extractedValues = {}, extractionFailures = [] } = chunk.data
|
|
1017
470
|
|
|
1018
|
-
|
|
1019
|
-
|
|
471
|
+
for (const [slug, value] of Object.entries(extractedValues)) {
|
|
472
|
+
console.log(`${operationType} extractor ${slug}:`, value)
|
|
473
|
+
}
|
|
1020
474
|
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
},
|
|
475
|
+
for (const failure of extractionFailures) {
|
|
476
|
+
console.error(`Extractor ${failure.slug} failed:`, failure.error)
|
|
477
|
+
}
|
|
478
|
+
}
|
|
1026
479
|
}
|
|
1027
480
|
```
|
|
1028
481
|
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
No manual migration needed. OM reads existing messages and observes them lazily when thresholds are exceeded.
|
|
1032
|
-
|
|
1033
|
-
- **Thread scope**: The first time a thread exceeds `observation.messageTokens`, the Observer processes the backlog.
|
|
1034
|
-
- **Resource scope (deprecated)**: All unobserved messages across all threads for a resource are processed together. For users with many existing threads, this could take substantial time.
|
|
1035
|
-
|
|
1036
|
-
## Comparing OM with other memory features
|
|
1037
|
-
|
|
1038
|
-
- **[Message history](https://mastra.ai/docs/memory/message-history)**: High-fidelity record of the current conversation
|
|
1039
|
-
- **[Working memory](https://mastra.ai/docs/memory/working-memory)**: Small, structured state (JSON or markdown) for user preferences, names, goals
|
|
1040
|
-
- **[Semantic Recall](https://mastra.ai/docs/memory/semantic-recall)**: RAG-based retrieval of relevant past messages
|
|
1041
|
-
- **[Multi-user threads](https://mastra.ai/docs/memory/multi-user-threads)**: How OM attributes facts to individual users when several people share a single thread
|
|
1042
|
-
|
|
1043
|
-
If you're using working memory to store conversation summaries or ongoing state that grows over time, OM is a better fit. Working memory is for small, structured data. OM is for long-running event logs. OM also manages message history automatically, the `messageTokens` setting controls how much raw history remains before observation runs.
|
|
482
|
+
`extractedValues` is keyed by each extractor's slug. Both fields are optional.
|
|
1044
483
|
|
|
1045
|
-
|
|
484
|
+
`data-om-observation-end` reports a synchronous completion. `data-om-buffering-end` reports finished background work: its extractor values are persisted at once, but the buffered observations stay inactive until activation. `operationType` says whether the work was an observation or a reflection. See [`data-om-observation-end`](https://mastra.ai/reference/memory/observational-memory) and [`data-om-buffering-end`](https://mastra.ai/reference/memory/observational-memory) for the payloads.
|
|
1046
485
|
|
|
1047
486
|
## Related
|
|
1048
487
|
|
|
1049
|
-
- [Observational Memory
|
|
1050
|
-
- [Memory
|
|
1051
|
-
- [
|
|
1052
|
-
- [Memory
|
|
1053
|
-
- [Mastra Code](https://code.mastra.ai/):
|
|
488
|
+
- [Observational Memory reference](https://mastra.ai/reference/memory/observational-memory)
|
|
489
|
+
- [Memory overview](https://mastra.ai/docs/memory/overview)
|
|
490
|
+
- [Multi-user threads](https://mastra.ai/docs/memory/multi-user-threads): how OM attributes facts to individual users in a shared thread
|
|
491
|
+
- [Memory processors](https://mastra.ai/docs/memory/memory-processors)
|
|
492
|
+
- [Mastra Code](https://code.mastra.ai/): a coding agent using Observational Memory
|
|
493
|
+
- [Mastra Factory](https://factory.mastra.ai/): a software factory whose agent sessions use Observational Memory
|
|
1054
494
|
- 📹 [Mastra processors and Observational Memory workshop](https://www.youtube.com/watch?v=4Vpp7xQYvl0)
|