@mastra/memory 1.0.0-beta.1 → 1.0.0-beta.11

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.
Files changed (73) hide show
  1. package/CHANGELOG.md +355 -0
  2. package/dist/_types/@internal_ai-sdk-v4/dist/index.d.ts +7549 -0
  3. package/dist/chunk-DGUM43GV.js +10 -0
  4. package/dist/chunk-DGUM43GV.js.map +1 -0
  5. package/dist/chunk-JEQ2X3Z6.cjs +12 -0
  6. package/dist/chunk-JEQ2X3Z6.cjs.map +1 -0
  7. package/dist/chunk-KMQS2YEC.js +79 -0
  8. package/dist/chunk-KMQS2YEC.js.map +1 -0
  9. package/dist/chunk-MMUHFOCG.js +79 -0
  10. package/dist/chunk-MMUHFOCG.js.map +1 -0
  11. package/dist/chunk-QY6BZOPJ.js +250 -0
  12. package/dist/chunk-QY6BZOPJ.js.map +1 -0
  13. package/dist/chunk-SG3GRV3O.cjs +84 -0
  14. package/dist/chunk-SG3GRV3O.cjs.map +1 -0
  15. package/dist/chunk-W72AYUIF.cjs +252 -0
  16. package/dist/chunk-W72AYUIF.cjs.map +1 -0
  17. package/dist/chunk-WC4XBMZT.js +250 -0
  18. package/dist/chunk-WC4XBMZT.js.map +1 -0
  19. package/dist/chunk-YMNW6DEN.cjs +252 -0
  20. package/dist/chunk-YMNW6DEN.cjs.map +1 -0
  21. package/dist/chunk-ZUQPUTTO.cjs +84 -0
  22. package/dist/chunk-ZUQPUTTO.cjs.map +1 -0
  23. package/dist/docs/README.md +36 -0
  24. package/dist/docs/SKILL.md +42 -0
  25. package/dist/docs/SOURCE_MAP.json +31 -0
  26. package/dist/docs/agents/01-agent-memory.md +160 -0
  27. package/dist/docs/agents/02-networks.md +236 -0
  28. package/dist/docs/agents/03-agent-approval.md +317 -0
  29. package/dist/docs/core/01-reference.md +114 -0
  30. package/dist/docs/memory/01-overview.md +76 -0
  31. package/dist/docs/memory/02-storage.md +181 -0
  32. package/dist/docs/memory/03-working-memory.md +386 -0
  33. package/dist/docs/memory/04-semantic-recall.md +235 -0
  34. package/dist/docs/memory/05-memory-processors.md +319 -0
  35. package/dist/docs/memory/06-reference.md +617 -0
  36. package/dist/docs/processors/01-reference.md +81 -0
  37. package/dist/docs/storage/01-reference.md +972 -0
  38. package/dist/docs/vectors/01-reference.md +929 -0
  39. package/dist/index.cjs +14845 -115
  40. package/dist/index.cjs.map +1 -1
  41. package/dist/index.d.ts +145 -5
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +14807 -119
  44. package/dist/index.js.map +1 -1
  45. package/dist/token-6GSAFR2W-JV3TZR4M.cjs +63 -0
  46. package/dist/token-6GSAFR2W-JV3TZR4M.cjs.map +1 -0
  47. package/dist/token-6GSAFR2W-K2BTU23I.js +61 -0
  48. package/dist/token-6GSAFR2W-K2BTU23I.js.map +1 -0
  49. package/dist/token-6GSAFR2W-VLY2XUPA.js +61 -0
  50. package/dist/token-6GSAFR2W-VLY2XUPA.js.map +1 -0
  51. package/dist/token-6GSAFR2W-YCB5SK2Z.cjs +63 -0
  52. package/dist/token-6GSAFR2W-YCB5SK2Z.cjs.map +1 -0
  53. package/dist/token-util-NEHG7TUY-7IL6JUVY.cjs +10 -0
  54. package/dist/token-util-NEHG7TUY-7IL6JUVY.cjs.map +1 -0
  55. package/dist/token-util-NEHG7TUY-HF7KBP2H.cjs +10 -0
  56. package/dist/token-util-NEHG7TUY-HF7KBP2H.cjs.map +1 -0
  57. package/dist/token-util-NEHG7TUY-KSXDO2NO.js +8 -0
  58. package/dist/token-util-NEHG7TUY-KSXDO2NO.js.map +1 -0
  59. package/dist/token-util-NEHG7TUY-TIJ3LMSH.js +8 -0
  60. package/dist/token-util-NEHG7TUY-TIJ3LMSH.js.map +1 -0
  61. package/dist/tools/working-memory.d.ts +10 -2
  62. package/dist/tools/working-memory.d.ts.map +1 -1
  63. package/package.json +19 -25
  64. package/dist/processors/index.cjs +0 -165
  65. package/dist/processors/index.cjs.map +0 -1
  66. package/dist/processors/index.d.ts +0 -3
  67. package/dist/processors/index.d.ts.map +0 -1
  68. package/dist/processors/index.js +0 -158
  69. package/dist/processors/index.js.map +0 -1
  70. package/dist/processors/token-limiter.d.ts +0 -32
  71. package/dist/processors/token-limiter.d.ts.map +0 -1
  72. package/dist/processors/tool-call-filter.d.ts +0 -20
  73. package/dist/processors/tool-call-filter.d.ts.map +0 -1
@@ -0,0 +1,235 @@
1
+ > Learn how to use semantic recall in Mastra to retrieve relevant messages from past conversations using vector search and embeddings.
2
+
3
+ # Semantic Recall
4
+
5
+ If you ask your friend what they did last weekend, they will search in their memory for events associated with "last weekend" and then tell you what they did. That's sort of like how semantic recall works in Mastra.
6
+
7
+ > **Watch 📹**
8
+
9
+ What semantic recall is, how it works, and how to configure it in Mastra → [YouTube (5 minutes)](https://youtu.be/UVZtK8cK8xQ)
10
+
11
+ ## How Semantic Recall Works
12
+
13
+ Semantic recall is RAG-based search that helps agents maintain context across longer interactions when messages are no longer within [recent message history](./message-history).
14
+
15
+ It uses vector embeddings of messages for similarity search, integrates with various vector stores, and has configurable context windows around retrieved messages.
16
+
17
+ ![Diagram showing Mastra Memory semantic recall](/img/semantic-recall.png)
18
+
19
+ When it's enabled, new messages are used to query a vector DB for semantically similar messages.
20
+
21
+ After getting a response from the LLM, all new messages (user, assistant, and tool calls/results) are inserted into the vector DB to be recalled in later interactions.
22
+
23
+ ## Quick Start
24
+
25
+ Semantic recall is enabled by default, so if you give your agent memory it will be included:
26
+
27
+ ```typescript {9}
28
+ import { Agent } from "@mastra/core/agent";
29
+ import { Memory } from "@mastra/memory";
30
+
31
+ const agent = new Agent({
32
+ id: "support-agent",
33
+ name: "SupportAgent",
34
+ instructions: "You are a helpful support agent.",
35
+ model: "openai/gpt-5.1",
36
+ memory: new Memory(),
37
+ });
38
+ ```
39
+
40
+ ## Storage configuration
41
+
42
+ Semantic recall relies on a [storage and vector db](https://mastra.ai/reference/v1/memory/memory-class) to store messages and their embeddings.
43
+
44
+ ```ts {8-16}
45
+ import { Memory } from "@mastra/memory";
46
+ import { Agent } from "@mastra/core/agent";
47
+ import { LibSQLStore, LibSQLVector } from "@mastra/libsql";
48
+
49
+ const agent = new Agent({
50
+ memory: new Memory({
51
+ // this is the default storage db if omitted
52
+ storage: new LibSQLStore({
53
+ id: 'agent-storage',
54
+ url: "file:./local.db",
55
+ }),
56
+ // this is the default vector db if omitted
57
+ vector: new LibSQLVector({
58
+ id: 'agent-vector',
59
+ connectionUrl: "file:./local.db",
60
+ }),
61
+ }),
62
+ });
63
+ ```
64
+
65
+ Each vector store page below includes installation instructions, configuration parameters, and usage examples:
66
+
67
+ - [Astra](https://mastra.ai/reference/v1/vectors/astra)
68
+ - [Chroma](https://mastra.ai/reference/v1/vectors/chroma)
69
+ - [Cloudflare Vectorize](https://mastra.ai/reference/v1/vectors/vectorize)
70
+ - [Convex](https://mastra.ai/reference/v1/vectors/convex)
71
+ - [Couchbase](https://mastra.ai/reference/v1/vectors/couchbase)
72
+ - [DuckDB](https://mastra.ai/reference/v1/vectors/duckdb)
73
+ - [Elasticsearch](https://mastra.ai/reference/v1/vectors/elasticsearch)
74
+ - [LanceDB](https://mastra.ai/reference/v1/vectors/lance)
75
+ - [libSQL](https://mastra.ai/reference/v1/vectors/libsql)
76
+ - [MongoDB](https://mastra.ai/reference/v1/vectors/mongodb)
77
+ - [OpenSearch](https://mastra.ai/reference/v1/vectors/opensearch)
78
+ - [Pinecone](https://mastra.ai/reference/v1/vectors/pinecone)
79
+ - [PostgreSQL](https://mastra.ai/reference/v1/vectors/pg)
80
+ - [Qdrant](https://mastra.ai/reference/v1/vectors/qdrant)
81
+ - [S3 Vectors](https://mastra.ai/reference/v1/vectors/s3vectors)
82
+ - [Turbopuffer](https://mastra.ai/reference/v1/vectors/turbopuffer)
83
+ - [Upstash](https://mastra.ai/reference/v1/vectors/upstash)
84
+
85
+ ## Recall configuration
86
+
87
+ The three main parameters that control semantic recall behavior are:
88
+
89
+ 1. **topK**: How many semantically similar messages to retrieve
90
+ 2. **messageRange**: How much surrounding context to include with each match
91
+ 3. **scope**: Whether to search within the current thread or across all threads owned by a resource (the default is resource scope).
92
+
93
+ ```typescript {5-7}
94
+ const agent = new Agent({
95
+ memory: new Memory({
96
+ options: {
97
+ semanticRecall: {
98
+ topK: 3, // Retrieve 3 most similar messages
99
+ messageRange: 2, // Include 2 messages before and after each match
100
+ scope: "resource", // Search across all threads for this user (default setting if omitted)
101
+ },
102
+ },
103
+ }),
104
+ });
105
+ ```
106
+
107
+ ## Embedder configuration
108
+
109
+ Semantic recall relies on an [embedding model](https://mastra.ai/reference/v1/memory/memory-class) to convert messages into embeddings. Mastra supports embedding models through the model router using `provider/model` strings, or you can use any [embedding model](https://sdk.vercel.ai/docs/ai-sdk-core/embeddings) compatible with the AI SDK.
110
+
111
+ #### Using the Model Router (Recommended)
112
+
113
+ The simplest way is to use a `provider/model` string with autocomplete support:
114
+
115
+ ```ts {7}
116
+ import { Memory } from "@mastra/memory";
117
+ import { Agent } from "@mastra/core/agent";
118
+ import { ModelRouterEmbeddingModel } from "@mastra/core/llm";
119
+
120
+ const agent = new Agent({
121
+ memory: new Memory({
122
+ embedder: new ModelRouterEmbeddingModel("openai/text-embedding-3-small"),
123
+ }),
124
+ });
125
+ ```
126
+
127
+ Supported embedding models:
128
+
129
+ - **OpenAI**: `text-embedding-3-small`, `text-embedding-3-large`, `text-embedding-ada-002`
130
+ - **Google**: `gemini-embedding-001`, `text-embedding-004`
131
+
132
+ The model router automatically handles API key detection from environment variables (`OPENAI_API_KEY`, `GOOGLE_GENERATIVE_AI_API_KEY`).
133
+
134
+ #### Using AI SDK Packages
135
+
136
+ You can also use AI SDK embedding models directly:
137
+
138
+ ```ts {2,7}
139
+ import { Memory } from "@mastra/memory";
140
+ import { Agent } from "@mastra/core/agent";
141
+ import { ModelRouterEmbeddingModel } from "@mastra/core/llm";
142
+
143
+ const agent = new Agent({
144
+ memory: new Memory({
145
+ embedder: new ModelRouterEmbeddingModel("openai/text-embedding-3-small"),
146
+ }),
147
+ });
148
+ ```
149
+
150
+ #### Using FastEmbed (Local)
151
+
152
+ To use FastEmbed (a local embedding model), install `@mastra/fastembed`:
153
+
154
+ ```bash npm2yarn
155
+ npm install @mastra/fastembed@beta
156
+ ```
157
+
158
+ Then configure it in your memory:
159
+
160
+ ```ts {3,7}
161
+ import { Memory } from "@mastra/memory";
162
+ import { Agent } from "@mastra/core/agent";
163
+ import { fastembed } from "@mastra/fastembed";
164
+
165
+ const agent = new Agent({
166
+ memory: new Memory({
167
+ embedder: fastembed,
168
+ }),
169
+ });
170
+ ```
171
+
172
+ ## PostgreSQL Index Optimization
173
+
174
+ When using PostgreSQL as your vector store, you can optimize semantic recall performance by configuring the vector index. This is particularly important for large-scale deployments with thousands of messages.
175
+
176
+ PostgreSQL supports both IVFFlat and HNSW indexes. By default, Mastra creates an IVFFlat index, but HNSW indexes typically provide better performance, especially with OpenAI embeddings which use inner product distance.
177
+
178
+ ```typescript {18-23}
179
+ import { Memory } from "@mastra/memory";
180
+ import { PgStore, PgVector } from "@mastra/pg";
181
+
182
+ const agent = new Agent({
183
+ memory: new Memory({
184
+ storage: new PgStore({
185
+ id: 'agent-storage',
186
+ connectionString: process.env.DATABASE_URL,
187
+ }),
188
+ vector: new PgVector({
189
+ id: 'agent-vector',
190
+ connectionString: process.env.DATABASE_URL,
191
+ }),
192
+ options: {
193
+ semanticRecall: {
194
+ topK: 5,
195
+ messageRange: 2,
196
+ indexConfig: {
197
+ type: "hnsw", // Use HNSW for better performance
198
+ metric: "dotproduct", // Best for OpenAI embeddings
199
+ m: 16, // Number of bi-directional links (default: 16)
200
+ efConstruction: 64, // Size of candidate list during construction (default: 64)
201
+ },
202
+ },
203
+ },
204
+ }),
205
+ });
206
+ ```
207
+
208
+ For detailed information about index configuration options and performance tuning, see the [PgVector configuration guide](https://mastra.ai/reference/v1/vectors/pg#index-configuration-guide).
209
+
210
+ ## Disabling
211
+
212
+ There is a performance impact to using semantic recall. New messages are converted into embeddings and used to query a vector database before new messages are sent to the LLM.
213
+
214
+ Semantic recall is enabled by default but can be disabled when not needed:
215
+
216
+ ```typescript {4}
217
+ const agent = new Agent({
218
+ memory: new Memory({
219
+ options: {
220
+ semanticRecall: false,
221
+ },
222
+ }),
223
+ });
224
+ ```
225
+
226
+ You might want to disable semantic recall in scenarios like:
227
+
228
+ - When message history provides sufficient context for the current conversation.
229
+ - In performance-sensitive applications, like realtime two-way audio, where the added latency of creating embeddings and running vector queries is noticeable.
230
+
231
+ ## Viewing Recalled Messages
232
+
233
+ When tracing is enabled, any messages retrieved via semantic recall will appear in the agent's trace output, alongside recent message history (if configured).
234
+
235
+ For more info on viewing message traces, see [Viewing Retrieved Messages](./overview#viewing-retrieved-messages).
@@ -0,0 +1,319 @@
1
+ > Learn how to use memory processors in Mastra to filter, trim, and transform messages before they
2
+
3
+ # Memory Processors
4
+
5
+ Memory processors transform and filter messages as they pass through an agent with memory enabled. They manage context window limits, remove unnecessary content, and optimize the information sent to the language model.
6
+
7
+ When memory is enabled on an agent, Mastra adds memory processors to the agent's processor pipeline. These processors retrieve message history, working memory, and semantically relevant messages, then persist new messages after the model responds.
8
+
9
+ Memory processors are [processors](https://mastra.ai/docs/v1/agents/processors) that operate specifically on memory-related messages and state.
10
+
11
+ ## Built-in Memory Processors
12
+
13
+ Mastra automatically adds these processors when memory is enabled:
14
+
15
+ ### MessageHistory
16
+
17
+ Retrieves message history and persists new messages.
18
+
19
+ **When you configure:**
20
+
21
+ ```typescript
22
+ memory: new Memory({
23
+ lastMessages: 10,
24
+ });
25
+ ```
26
+
27
+ **Mastra internally:**
28
+
29
+ 1. Creates a `MessageHistory` processor with `limit: 10`
30
+ 2. Adds it to the agent's input processors (runs before the LLM)
31
+ 3. Adds it to the agent's output processors (runs after the LLM)
32
+
33
+ **What it does:**
34
+
35
+ - **Input**: Fetches the last 10 messages from storage and prepends them to the conversation
36
+ - **Output**: Persists new messages to storage after the model responds
37
+
38
+ **Example:**
39
+
40
+ ```typescript
41
+ import { Agent } from "@mastra/core/agent";
42
+ import { Memory } from "@mastra/memory";
43
+ import { LibSQLStore } from "@mastra/libsql";
44
+ import { openai } from "@ai-sdk/openai";
45
+
46
+ const agent = new Agent({
47
+ id: "test-agent",
48
+ name: "Test Agent",
49
+ instructions: "You are a helpful assistant",
50
+ model: 'openai/gpt-4o',
51
+ memory: new Memory({
52
+ storage: new LibSQLStore({
53
+ id: "memory-store",
54
+ url: "file:memory.db",
55
+ }),
56
+ lastMessages: 10, // MessageHistory processor automatically added
57
+ }),
58
+ });
59
+ ```
60
+
61
+ ### SemanticRecall
62
+
63
+ Retrieves semantically relevant messages based on the current input and creates embeddings for new messages.
64
+
65
+ **When you configure:**
66
+
67
+ ```typescript
68
+ memory: new Memory({
69
+ semanticRecall: { enabled: true },
70
+ vector: myVectorStore,
71
+ embedder: myEmbedder,
72
+ });
73
+ ```
74
+
75
+ **Mastra internally:**
76
+
77
+ 1. Creates a `SemanticRecall` processor
78
+ 2. Adds it to the agent's input processors (runs before the LLM)
79
+ 3. Adds it to the agent's output processors (runs after the LLM)
80
+ 4. Requires both a vector store and embedder to be configured
81
+
82
+ **What it does:**
83
+
84
+ - **Input**: Performs vector similarity search to find relevant past messages and prepends them to the conversation
85
+ - **Output**: Creates embeddings for new messages and stores them in the vector store for future retrieval
86
+
87
+ **Example:**
88
+
89
+ ```typescript
90
+ import { Agent } from "@mastra/core/agent";
91
+ import { Memory } from "@mastra/memory";
92
+ import { LibSQLStore } from "@mastra/libsql";
93
+ import { PineconeVector } from "@mastra/pinecone";
94
+ import { OpenAIEmbedder } from "@mastra/openai";
95
+ import { openai } from "@ai-sdk/openai";
96
+
97
+ const agent = new Agent({
98
+ name: "semantic-agent",
99
+ instructions: "You are a helpful assistant with semantic memory",
100
+ model: 'openai/gpt-4o',
101
+ memory: new Memory({
102
+ storage: new LibSQLStore({
103
+ id: "memory-store",
104
+ url: "file:memory.db",
105
+ }),
106
+ vector: new PineconeVector({
107
+ id: "memory-vector",
108
+ apiKey: process.env.PINECONE_API_KEY!,
109
+ environment: "us-east-1",
110
+ }),
111
+ embedder: new OpenAIEmbedder({
112
+ model: "text-embedding-3-small",
113
+ apiKey: process.env.OPENAI_API_KEY!,
114
+ }),
115
+ semanticRecall: { enabled: true }, // SemanticRecall processor automatically added
116
+ }),
117
+ });
118
+ ```
119
+
120
+ ### WorkingMemory
121
+
122
+ Manages working memory state across conversations.
123
+
124
+ **When you configure:**
125
+
126
+ ```typescript
127
+ memory: new Memory({
128
+ workingMemory: { enabled: true },
129
+ });
130
+ ```
131
+
132
+ **Mastra internally:**
133
+
134
+ 1. Creates a `WorkingMemory` processor
135
+ 2. Adds it to the agent's input processors (runs before the LLM)
136
+ 3. Requires a storage adapter to be configured
137
+
138
+ **What it does:**
139
+
140
+ - **Input**: Retrieves working memory state for the current thread and prepends it to the conversation
141
+ - **Output**: No output processing
142
+
143
+ **Example:**
144
+
145
+ ```typescript
146
+ import { Agent } from "@mastra/core/agent";
147
+ import { Memory } from "@mastra/memory";
148
+ import { LibSQLStore } from "@mastra/libsql";
149
+ import { openai } from "@ai-sdk/openai";
150
+
151
+ const agent = new Agent({
152
+ name: "working-memory-agent",
153
+ instructions: "You are an assistant with working memory",
154
+ model: 'openai/gpt-4o',
155
+ memory: new Memory({
156
+ storage: new LibSQLStore({
157
+ id: "memory-store",
158
+ url: "file:memory.db",
159
+ }),
160
+ workingMemory: { enabled: true }, // WorkingMemory processor automatically added
161
+ }),
162
+ });
163
+ ```
164
+
165
+ ## Manual Control and Deduplication
166
+
167
+ If you manually add a memory processor to `inputProcessors` or `outputProcessors`, Mastra will **not** automatically add it. This gives you full control over processor ordering:
168
+
169
+ ```typescript
170
+ import { Agent } from "@mastra/core/agent";
171
+ import { Memory } from "@mastra/memory";
172
+ import { MessageHistory } from "@mastra/memory/processors";
173
+ import { TokenLimiter } from "@mastra/core/processors";
174
+ import { LibSQLStore } from "@mastra/libsql";
175
+ import { openai } from "@ai-sdk/openai";
176
+
177
+ // Custom MessageHistory with different configuration
178
+ const customMessageHistory = new MessageHistory({
179
+ storage: new LibSQLStore({ id: "memory-store", url: "file:memory.db" }),
180
+ lastMessages: 20,
181
+ });
182
+
183
+ const agent = new Agent({
184
+ name: "custom-memory-agent",
185
+ instructions: "You are a helpful assistant",
186
+ model: 'openai/gpt-4o',
187
+ memory: new Memory({
188
+ storage: new LibSQLStore({ id: "memory-store", url: "file:memory.db" }),
189
+ lastMessages: 10, // This would normally add MessageHistory(10)
190
+ }),
191
+ inputProcessors: [
192
+ customMessageHistory, // Your custom one is used instead
193
+ new TokenLimiter({ limit: 4000 }), // Runs after your custom MessageHistory
194
+ ],
195
+ });
196
+ ```
197
+
198
+ ## Processor Execution Order
199
+
200
+ Understanding the execution order is important when combining guardrails with memory:
201
+
202
+ ### Input Processors
203
+
204
+ ```
205
+ [Memory Processors] → [Your inputProcessors]
206
+ ```
207
+
208
+ 1. **Memory processors run FIRST**: `WorkingMemory`, `MessageHistory`, `SemanticRecall`
209
+ 2. **Your input processors run AFTER**: guardrails, filters, validators
210
+
211
+ This means memory loads message history before your processors can validate or filter the input.
212
+
213
+ ### Output Processors
214
+
215
+ ```
216
+ [Your outputProcessors] → [Memory Processors]
217
+ ```
218
+
219
+ 1. **Your output processors run FIRST**: guardrails, filters, validators
220
+ 2. **Memory processors run AFTER**: `SemanticRecall` (embeddings), `MessageHistory` (persistence)
221
+
222
+ This ordering is designed to be **safe by default**: if your output guardrail calls `abort()`, the memory processors never run and **no messages are saved**.
223
+
224
+ ## Guardrails and Memory
225
+
226
+ The default execution order provides safe guardrail behavior:
227
+
228
+ ### Output guardrails (recommended)
229
+
230
+ Output guardrails run **before** memory processors save messages. If a guardrail aborts:
231
+
232
+ - The tripwire is triggered
233
+ - Memory processors are skipped
234
+ - **No messages are persisted to storage**
235
+
236
+ ```typescript
237
+ import { Agent } from "@mastra/core/agent";
238
+ import { Memory } from "@mastra/memory";
239
+ import { openai } from "@ai-sdk/openai";
240
+
241
+ // Output guardrail that blocks inappropriate content
242
+ const contentBlocker = {
243
+ id: "content-blocker",
244
+ processOutputResult: async ({ messages, abort }) => {
245
+ const hasInappropriateContent = messages.some((msg) =>
246
+ containsBadContent(msg)
247
+ );
248
+ if (hasInappropriateContent) {
249
+ abort("Content blocked by guardrail");
250
+ }
251
+ return messages;
252
+ },
253
+ };
254
+
255
+ const agent = new Agent({
256
+ name: "safe-agent",
257
+ instructions: "You are a helpful assistant",
258
+ model: 'openai/gpt-4o',
259
+ memory: new Memory({ lastMessages: 10 }),
260
+ // Your guardrail runs BEFORE memory saves
261
+ outputProcessors: [contentBlocker],
262
+ });
263
+
264
+ // If the guardrail aborts, nothing is saved to memory
265
+ const result = await agent.generate("Hello");
266
+ if (result.tripwire) {
267
+ console.log("Blocked:", result.tripwireReason);
268
+ // Memory is empty - no messages were persisted
269
+ }
270
+ ```
271
+
272
+ ### Input guardrails
273
+
274
+ Input guardrails run **after** memory processors load history. If a guardrail aborts:
275
+
276
+ - The tripwire is triggered
277
+ - The LLM is never called
278
+ - Output processors (including memory persistence) are skipped
279
+ - **No messages are persisted to storage**
280
+
281
+ ```typescript
282
+ // Input guardrail that validates user input
283
+ const inputValidator = {
284
+ id: "input-validator",
285
+ processInput: async ({ messages, abort }) => {
286
+ const lastUserMessage = messages.findLast((m) => m.role === "user");
287
+ if (isInvalidInput(lastUserMessage)) {
288
+ abort("Invalid input detected");
289
+ }
290
+ return messages;
291
+ },
292
+ };
293
+
294
+ const agent = new Agent({
295
+ name: "validated-agent",
296
+ instructions: "You are a helpful assistant",
297
+ model: 'openai/gpt-4o',
298
+ memory: new Memory({ lastMessages: 10 }),
299
+ // Your guardrail runs AFTER memory loads history
300
+ inputProcessors: [inputValidator],
301
+ });
302
+ ```
303
+
304
+ ### Summary
305
+
306
+ | Guardrail Type | When it runs | If it aborts |
307
+ | -------------- | ------------ | ------------ |
308
+ | Input | After memory loads history | LLM not called, nothing saved |
309
+ | Output | Before memory saves | Nothing saved to storage |
310
+
311
+ Both scenarios are safe - guardrails prevent inappropriate content from being persisted to memory
312
+
313
+ ## Related documentation
314
+
315
+ - [Processors](https://mastra.ai/docs/v1/agents/processors) - General processor concepts and custom processor creation
316
+ - [Guardrails](https://mastra.ai/docs/v1/agents/guardrails) - Security and validation processors
317
+ - [Memory Overview](https://mastra.ai/docs/v1/memory/overview) - Memory types and configuration
318
+
319
+ When creating custom processors avoid mutating the input `messages` array or its objects directly.