@mastra/libsql 0.0.0-error-handler-fix-20251020202607 → 0.0.0-everlasting-joggers-20260331153923
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/CHANGELOG.md +3120 -3
- package/LICENSE.md +15 -0
- package/README.md +30 -20
- package/dist/docs/SKILL.md +46 -0
- package/dist/docs/assets/SOURCE_MAP.json +6 -0
- package/dist/docs/references/docs-agents-agent-approval.md +509 -0
- package/dist/docs/references/docs-agents-networks.md +182 -0
- package/dist/docs/references/docs-memory-memory-processors.md +314 -0
- package/dist/docs/references/docs-memory-message-history.md +262 -0
- package/dist/docs/references/docs-memory-overview.md +240 -0
- package/dist/docs/references/docs-memory-semantic-recall.md +297 -0
- package/dist/docs/references/docs-memory-storage.md +261 -0
- package/dist/docs/references/docs-memory-working-memory.md +400 -0
- package/dist/docs/references/docs-rag-retrieval.md +515 -0
- package/dist/docs/references/docs-workflows-snapshots.md +238 -0
- package/dist/docs/references/guides-agent-frameworks-ai-sdk.md +140 -0
- package/dist/docs/references/reference-core-getMemory.md +49 -0
- package/dist/docs/references/reference-core-listMemory.md +55 -0
- package/dist/docs/references/reference-core-mastra-class.md +66 -0
- package/dist/docs/references/reference-memory-memory-class.md +145 -0
- package/dist/docs/references/reference-storage-composite.md +243 -0
- package/dist/docs/references/reference-storage-dynamodb.md +282 -0
- package/dist/docs/references/reference-storage-libsql.md +135 -0
- package/dist/docs/references/reference-vectors-libsql.md +305 -0
- package/dist/index.cjs +9006 -1972
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +8993 -1973
- package/dist/index.js.map +1 -1
- package/dist/storage/db/index.d.ts +318 -0
- package/dist/storage/db/index.d.ts.map +1 -0
- package/dist/storage/{domains → db}/utils.d.ts +21 -13
- package/dist/storage/db/utils.d.ts.map +1 -0
- package/dist/storage/domains/agents/index.d.ts +30 -0
- package/dist/storage/domains/agents/index.d.ts.map +1 -0
- package/dist/storage/domains/blobs/index.d.ts +17 -0
- package/dist/storage/domains/blobs/index.d.ts.map +1 -0
- package/dist/storage/domains/datasets/index.d.ts +43 -0
- package/dist/storage/domains/datasets/index.d.ts.map +1 -0
- package/dist/storage/domains/experiments/index.d.ts +31 -0
- package/dist/storage/domains/experiments/index.d.ts.map +1 -0
- package/dist/storage/domains/mcp-clients/index.d.ts +26 -0
- package/dist/storage/domains/mcp-clients/index.d.ts.map +1 -0
- package/dist/storage/domains/mcp-servers/index.d.ts +26 -0
- package/dist/storage/domains/mcp-servers/index.d.ts.map +1 -0
- package/dist/storage/domains/memory/index.d.ts +41 -53
- package/dist/storage/domains/memory/index.d.ts.map +1 -1
- package/dist/storage/domains/observability/index.d.ts +41 -29
- package/dist/storage/domains/observability/index.d.ts.map +1 -1
- package/dist/storage/domains/prompt-blocks/index.d.ts +25 -0
- package/dist/storage/domains/prompt-blocks/index.d.ts.map +1 -0
- package/dist/storage/domains/scorer-definitions/index.d.ts +26 -0
- package/dist/storage/domains/scorer-definitions/index.d.ts.map +1 -0
- package/dist/storage/domains/scores/index.d.ts +19 -31
- package/dist/storage/domains/scores/index.d.ts.map +1 -1
- package/dist/storage/domains/skills/index.d.ts +26 -0
- package/dist/storage/domains/skills/index.d.ts.map +1 -0
- package/dist/storage/domains/workflows/index.d.ts +20 -32
- package/dist/storage/domains/workflows/index.d.ts.map +1 -1
- package/dist/storage/domains/workspaces/index.d.ts +26 -0
- package/dist/storage/domains/workspaces/index.d.ts.map +1 -0
- package/dist/storage/index.d.ts +68 -259
- package/dist/storage/index.d.ts.map +1 -1
- package/dist/vector/index.d.ts +12 -4
- package/dist/vector/index.d.ts.map +1 -1
- package/dist/vector/sql-builder.d.ts.map +1 -1
- package/package.json +17 -13
- package/dist/storage/domains/legacy-evals/index.d.ts +0 -18
- package/dist/storage/domains/legacy-evals/index.d.ts.map +0 -1
- package/dist/storage/domains/operations/index.d.ts +0 -110
- package/dist/storage/domains/operations/index.d.ts.map +0 -1
- package/dist/storage/domains/traces/index.d.ts +0 -21
- package/dist/storage/domains/traces/index.d.ts.map +0 -1
- package/dist/storage/domains/utils.d.ts.map +0 -1
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
# Agent networks
|
|
2
|
+
|
|
3
|
+
> **Deprecated — Use supervisor agents:** Agent networks are deprecated and will be removed in a future major release. [Supervisor agents](https://mastra.ai/docs/agents/supervisor-agents) using `agent.stream()` or `agent.generate()` are now the recommended approach. It provides the same multi-agent coordination with better control, a simpler API, and easier debugging.
|
|
4
|
+
>
|
|
5
|
+
> See the [migration guide](https://mastra.ai/guides/migrations/network-to-supervisor) to upgrade.
|
|
6
|
+
|
|
7
|
+
A **routing agent** uses an LLM to interpret a request and decide which primitives (subagents, workflows, or tools) to call, in what order, and with what data.
|
|
8
|
+
|
|
9
|
+
## Create an agent network
|
|
10
|
+
|
|
11
|
+
Configure a routing agent with `agents`, `workflows`, and `tools`. Memory is required as `.network()` uses it to store task history and determine when a task is complete.
|
|
12
|
+
|
|
13
|
+
Each primitive needs a clear `description` so the routing agent can decide which to use. For workflows and tools, `inputSchema` and `outputSchema` also help the router determine the right inputs.
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
import { Agent } from '@mastra/core/agent'
|
|
17
|
+
import { Memory } from '@mastra/memory'
|
|
18
|
+
import { LibSQLStore } from '@mastra/libsql'
|
|
19
|
+
|
|
20
|
+
import { researchAgent } from './research-agent'
|
|
21
|
+
import { writingAgent } from './writing-agent'
|
|
22
|
+
import { cityWorkflow } from '../workflows/city-workflow'
|
|
23
|
+
import { weatherTool } from '../tools/weather-tool'
|
|
24
|
+
|
|
25
|
+
export const routingAgent = new Agent({
|
|
26
|
+
id: 'routing-agent',
|
|
27
|
+
name: 'Routing Agent',
|
|
28
|
+
instructions: `
|
|
29
|
+
You are a network of writers and researchers. The user will ask you to research a topic. Always respond with a complete report—no bullet points. Write in full paragraphs, like a blog post. Do not answer with incomplete or uncertain information.`,
|
|
30
|
+
model: 'openai/gpt-5.4',
|
|
31
|
+
agents: {
|
|
32
|
+
researchAgent,
|
|
33
|
+
writingAgent,
|
|
34
|
+
},
|
|
35
|
+
workflows: {
|
|
36
|
+
cityWorkflow,
|
|
37
|
+
},
|
|
38
|
+
tools: {
|
|
39
|
+
weatherTool,
|
|
40
|
+
},
|
|
41
|
+
memory: new Memory({
|
|
42
|
+
storage: new LibSQLStore({
|
|
43
|
+
id: 'mastra-storage',
|
|
44
|
+
url: 'file:../mastra.db',
|
|
45
|
+
}),
|
|
46
|
+
}),
|
|
47
|
+
})
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
> **Note:** Subagents need a `description` on the `Agent` instance. Workflows and tools need a `description` plus `inputSchema` and `outputSchema` on `createWorkflow()` or `createTool()`.
|
|
51
|
+
|
|
52
|
+
## Call the network
|
|
53
|
+
|
|
54
|
+
Call `.network()` with a user message. The method returns a stream of events you can iterate over.
|
|
55
|
+
|
|
56
|
+
```typescript
|
|
57
|
+
const result = await routingAgent.network('Tell me three cool ways to use Mastra')
|
|
58
|
+
|
|
59
|
+
for await (const chunk of result) {
|
|
60
|
+
console.log(chunk.type)
|
|
61
|
+
if (chunk.type === 'network-execution-event-step-finish') {
|
|
62
|
+
console.log(chunk.payload.result)
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Structured output
|
|
68
|
+
|
|
69
|
+
Pass `structuredOutput` to get typed, validated results. Use `objectStream` for partial objects as they generate.
|
|
70
|
+
|
|
71
|
+
```typescript
|
|
72
|
+
import { z } from 'zod'
|
|
73
|
+
|
|
74
|
+
const resultSchema = z.object({
|
|
75
|
+
summary: z.string().describe('A brief summary of the findings'),
|
|
76
|
+
recommendations: z.array(z.string()).describe('List of recommendations'),
|
|
77
|
+
confidence: z.number().min(0).max(1).describe('Confidence score'),
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
const stream = await routingAgent.network('Research AI trends', {
|
|
81
|
+
structuredOutput: { schema: resultSchema },
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
for await (const partial of stream.objectStream) {
|
|
85
|
+
console.log('Building result:', partial)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const final = await stream.object
|
|
89
|
+
console.log(final?.summary)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Approve and decline tool calls
|
|
93
|
+
|
|
94
|
+
When a primitive requires approval, the stream emits an `agent-execution-approval` or `tool-execution-approval` chunk. Use `approveNetworkToolCall()` or `declineNetworkToolCall()` to respond.
|
|
95
|
+
|
|
96
|
+
Network approval uses snapshots to capture execution state. Ensure a [storage provider](https://mastra.ai/docs/memory/storage) is enabled in your Mastra instance.
|
|
97
|
+
|
|
98
|
+
```typescript
|
|
99
|
+
const stream = await routingAgent.network('Perform some sensitive action', {
|
|
100
|
+
memory: {
|
|
101
|
+
thread: 'user-123',
|
|
102
|
+
resource: 'my-app',
|
|
103
|
+
},
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
for await (const chunk of stream) {
|
|
107
|
+
if (chunk.type === 'agent-execution-approval' || chunk.type === 'tool-execution-approval') {
|
|
108
|
+
// Approve
|
|
109
|
+
const approvedStream = await routingAgent.approveNetworkToolCall(chunk.payload.toolCallId, {
|
|
110
|
+
runId: stream.runId,
|
|
111
|
+
memory: { thread: 'user-123', resource: 'my-app' },
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
for await (const c of approvedStream) {
|
|
115
|
+
if (c.type === 'network-execution-event-step-finish') {
|
|
116
|
+
console.log(c.payload.result)
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
To decline instead, call `declineNetworkToolCall()` with the same arguments.
|
|
124
|
+
|
|
125
|
+
## Suspend and resume
|
|
126
|
+
|
|
127
|
+
When a primitive calls `suspend()`, the stream emits a suspension chunk (e.g., `tool-execution-suspended`). Use `resumeNetwork()` to provide the requested data and continue execution.
|
|
128
|
+
|
|
129
|
+
```typescript
|
|
130
|
+
const stream = await routingAgent.network('Delete the old records', {
|
|
131
|
+
memory: { thread: 'user-123', resource: 'my-app' },
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
for await (const chunk of stream) {
|
|
135
|
+
if (chunk.type === 'workflow-execution-suspended') {
|
|
136
|
+
console.log(chunk.payload.suspendPayload)
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Resume with user confirmation
|
|
141
|
+
const resumedStream = await routingAgent.resumeNetwork(
|
|
142
|
+
{ confirmed: true },
|
|
143
|
+
{
|
|
144
|
+
runId: stream.runId,
|
|
145
|
+
memory: { thread: 'user-123', resource: 'my-app' },
|
|
146
|
+
},
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
for await (const chunk of resumedStream) {
|
|
150
|
+
if (chunk.type === 'network-execution-event-step-finish') {
|
|
151
|
+
console.log(chunk.payload.result)
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### Automatic resumption
|
|
157
|
+
|
|
158
|
+
Set `autoResumeSuspendedTools` to `true` so the network resumes suspended primitives based on the user's next message. This creates a conversational flow where users provide the required information naturally.
|
|
159
|
+
|
|
160
|
+
```typescript
|
|
161
|
+
const stream = await routingAgent.network('Delete the old records', {
|
|
162
|
+
autoResumeSuspendedTools: true,
|
|
163
|
+
memory: { thread: 'user-123', resource: 'my-app' },
|
|
164
|
+
})
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Requirements for automatic resumption:
|
|
168
|
+
|
|
169
|
+
- **Memory configured**: The agent needs memory to track suspended tools across messages.
|
|
170
|
+
- **Same thread**: The follow-up message must use the same `thread` and `resource` identifiers.
|
|
171
|
+
- **`resumeSchema` defined**: The tool must define a `resumeSchema` so the network can extract data from the user's message.
|
|
172
|
+
|
|
173
|
+
| | Manual (`resumeNetwork`) | Automatic (`autoResumeSuspendedTools`) |
|
|
174
|
+
| -------- | ---------------------------------------------- | ----------------------------------------- |
|
|
175
|
+
| Best for | Custom UIs with approval buttons | Chat-style interfaces |
|
|
176
|
+
| Control | Full control over resume timing and data | Network extracts data from user's message |
|
|
177
|
+
| Setup | Handle suspension chunks, call `resumeNetwork` | Set flag, define `resumeSchema` on tools |
|
|
178
|
+
|
|
179
|
+
## Related
|
|
180
|
+
|
|
181
|
+
- [Supervisor agents](https://mastra.ai/docs/agents/supervisor-agents)
|
|
182
|
+
- [Migration: `.network()` to supervisor agents](https://mastra.ai/guides/migrations/network-to-supervisor)
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
# Memory processors
|
|
2
|
+
|
|
3
|
+
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.
|
|
4
|
+
|
|
5
|
+
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.
|
|
6
|
+
|
|
7
|
+
Memory processors are [processors](https://mastra.ai/docs/agents/processors) that operate specifically on memory-related messages and state.
|
|
8
|
+
|
|
9
|
+
## Built-in memory processors
|
|
10
|
+
|
|
11
|
+
Mastra automatically adds these processors when memory is enabled:
|
|
12
|
+
|
|
13
|
+
### `MessageHistory`
|
|
14
|
+
|
|
15
|
+
Retrieves message history and persists new messages.
|
|
16
|
+
|
|
17
|
+
**When you configure:**
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
memory: new Memory({
|
|
21
|
+
lastMessages: 10,
|
|
22
|
+
})
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
**Mastra internally:**
|
|
26
|
+
|
|
27
|
+
1. Creates a `MessageHistory` processor with `limit: 10`
|
|
28
|
+
2. Adds it to the agent's input processors (runs before the LLM)
|
|
29
|
+
3. Adds it to the agent's output processors (runs after the LLM)
|
|
30
|
+
|
|
31
|
+
**What it does:**
|
|
32
|
+
|
|
33
|
+
- **Input**: Fetches the last 10 messages from storage and prepends them to the conversation
|
|
34
|
+
- **Output**: Persists new messages to storage after the model responds
|
|
35
|
+
|
|
36
|
+
**Example:**
|
|
37
|
+
|
|
38
|
+
```typescript
|
|
39
|
+
import { Agent } from '@mastra/core/agent'
|
|
40
|
+
import { Memory } from '@mastra/memory'
|
|
41
|
+
import { LibSQLStore } from '@mastra/libsql'
|
|
42
|
+
import { openai } from '@ai-sdk/openai'
|
|
43
|
+
|
|
44
|
+
const agent = new Agent({
|
|
45
|
+
id: 'test-agent',
|
|
46
|
+
name: 'Test Agent',
|
|
47
|
+
instructions: 'You are a helpful assistant',
|
|
48
|
+
model: 'openai/gpt-5.4',
|
|
49
|
+
memory: new Memory({
|
|
50
|
+
storage: new LibSQLStore({
|
|
51
|
+
id: 'memory-store',
|
|
52
|
+
url: 'file:memory.db',
|
|
53
|
+
}),
|
|
54
|
+
lastMessages: 10, // MessageHistory processor automatically added
|
|
55
|
+
}),
|
|
56
|
+
})
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### `SemanticRecall`
|
|
60
|
+
|
|
61
|
+
Retrieves semantically relevant messages based on the current input and creates embeddings for new messages.
|
|
62
|
+
|
|
63
|
+
**When you configure:**
|
|
64
|
+
|
|
65
|
+
```typescript
|
|
66
|
+
memory: new Memory({
|
|
67
|
+
semanticRecall: { enabled: true },
|
|
68
|
+
vector: myVectorStore,
|
|
69
|
+
embedder: myEmbedder,
|
|
70
|
+
})
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
**Mastra internally:**
|
|
74
|
+
|
|
75
|
+
1. Creates a `SemanticRecall` processor
|
|
76
|
+
2. Adds it to the agent's input processors (runs before the LLM)
|
|
77
|
+
3. Adds it to the agent's output processors (runs after the LLM)
|
|
78
|
+
4. Requires both a vector store and embedder to be configured
|
|
79
|
+
|
|
80
|
+
**What it does:**
|
|
81
|
+
|
|
82
|
+
- **Input**: Performs vector similarity search to find relevant past messages and prepends them to the conversation
|
|
83
|
+
- **Output**: Creates embeddings for new messages and stores them in the vector store for future retrieval
|
|
84
|
+
|
|
85
|
+
**Example:**
|
|
86
|
+
|
|
87
|
+
```typescript
|
|
88
|
+
import { Agent } from '@mastra/core/agent'
|
|
89
|
+
import { Memory } from '@mastra/memory'
|
|
90
|
+
import { LibSQLStore } from '@mastra/libsql'
|
|
91
|
+
import { PineconeVector } from '@mastra/pinecone'
|
|
92
|
+
import { OpenAIEmbedder } from '@mastra/openai'
|
|
93
|
+
import { openai } from '@ai-sdk/openai'
|
|
94
|
+
|
|
95
|
+
const agent = new Agent({
|
|
96
|
+
name: 'semantic-agent',
|
|
97
|
+
instructions: 'You are a helpful assistant with semantic memory',
|
|
98
|
+
model: 'openai/gpt-5.4',
|
|
99
|
+
memory: new Memory({
|
|
100
|
+
storage: new LibSQLStore({
|
|
101
|
+
id: 'memory-store',
|
|
102
|
+
url: 'file:memory.db',
|
|
103
|
+
}),
|
|
104
|
+
vector: new PineconeVector({
|
|
105
|
+
id: 'memory-vector',
|
|
106
|
+
apiKey: process.env.PINECONE_API_KEY!,
|
|
107
|
+
}),
|
|
108
|
+
embedder: new OpenAIEmbedder({
|
|
109
|
+
model: 'text-embedding-3-small',
|
|
110
|
+
apiKey: process.env.OPENAI_API_KEY!,
|
|
111
|
+
}),
|
|
112
|
+
semanticRecall: { enabled: true }, // SemanticRecall processor automatically added
|
|
113
|
+
}),
|
|
114
|
+
})
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
### `WorkingMemory`
|
|
118
|
+
|
|
119
|
+
Manages working memory state across conversations.
|
|
120
|
+
|
|
121
|
+
**When you configure:**
|
|
122
|
+
|
|
123
|
+
```typescript
|
|
124
|
+
memory: new Memory({
|
|
125
|
+
workingMemory: { enabled: true },
|
|
126
|
+
})
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
**Mastra internally:**
|
|
130
|
+
|
|
131
|
+
1. Creates a `WorkingMemory` processor
|
|
132
|
+
2. Adds it to the agent's input processors (runs before the LLM)
|
|
133
|
+
3. Requires a storage adapter to be configured
|
|
134
|
+
|
|
135
|
+
**What it does:**
|
|
136
|
+
|
|
137
|
+
- **Input**: Retrieves working memory state for the current thread and prepends it to the conversation
|
|
138
|
+
- **Output**: No output processing
|
|
139
|
+
|
|
140
|
+
**Example:**
|
|
141
|
+
|
|
142
|
+
```typescript
|
|
143
|
+
import { Agent } from '@mastra/core/agent'
|
|
144
|
+
import { Memory } from '@mastra/memory'
|
|
145
|
+
import { LibSQLStore } from '@mastra/libsql'
|
|
146
|
+
import { openai } from '@ai-sdk/openai'
|
|
147
|
+
|
|
148
|
+
const agent = new Agent({
|
|
149
|
+
name: 'working-memory-agent',
|
|
150
|
+
instructions: 'You are an assistant with working memory',
|
|
151
|
+
model: 'openai/gpt-5.4',
|
|
152
|
+
memory: new Memory({
|
|
153
|
+
storage: new LibSQLStore({
|
|
154
|
+
id: 'memory-store',
|
|
155
|
+
url: 'file:memory.db',
|
|
156
|
+
}),
|
|
157
|
+
workingMemory: { enabled: true }, // WorkingMemory processor automatically added
|
|
158
|
+
}),
|
|
159
|
+
})
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
## Manual control and deduplication
|
|
163
|
+
|
|
164
|
+
If you manually add a memory processor to `inputProcessors` or `outputProcessors`, Mastra **won't** automatically add it. This gives you full control over processor ordering:
|
|
165
|
+
|
|
166
|
+
```typescript
|
|
167
|
+
import { Agent } from '@mastra/core/agent'
|
|
168
|
+
import { Memory } from '@mastra/memory'
|
|
169
|
+
import { MessageHistory } from '@mastra/core/processors'
|
|
170
|
+
import { TokenLimiter } from '@mastra/core/processors'
|
|
171
|
+
import { LibSQLStore } from '@mastra/libsql'
|
|
172
|
+
import { openai } from '@ai-sdk/openai'
|
|
173
|
+
|
|
174
|
+
// Custom MessageHistory with different configuration
|
|
175
|
+
const customMessageHistory = new MessageHistory({
|
|
176
|
+
storage: new LibSQLStore({ id: 'memory-store', url: 'file:memory.db' }),
|
|
177
|
+
lastMessages: 20,
|
|
178
|
+
})
|
|
179
|
+
|
|
180
|
+
const agent = new Agent({
|
|
181
|
+
name: 'custom-memory-agent',
|
|
182
|
+
instructions: 'You are a helpful assistant',
|
|
183
|
+
model: 'openai/gpt-5.4',
|
|
184
|
+
memory: new Memory({
|
|
185
|
+
storage: new LibSQLStore({ id: 'memory-store', url: 'file:memory.db' }),
|
|
186
|
+
lastMessages: 10, // This would normally add MessageHistory(10)
|
|
187
|
+
}),
|
|
188
|
+
inputProcessors: [
|
|
189
|
+
customMessageHistory, // Your custom one is used instead
|
|
190
|
+
new TokenLimiter({ limit: 4000 }), // Runs after your custom MessageHistory
|
|
191
|
+
],
|
|
192
|
+
})
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
## Processor execution order
|
|
196
|
+
|
|
197
|
+
Understanding the execution order is important when combining guardrails with memory:
|
|
198
|
+
|
|
199
|
+
### Input Processors
|
|
200
|
+
|
|
201
|
+
```text
|
|
202
|
+
[Memory Processors] → [Your inputProcessors]
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
1. **Memory processors run FIRST**: `WorkingMemory`, `MessageHistory`, `SemanticRecall`
|
|
206
|
+
2. **Your input processors run AFTER**: guardrails, filters, validators
|
|
207
|
+
|
|
208
|
+
This means memory loads message history before your processors can validate or filter the input.
|
|
209
|
+
|
|
210
|
+
### Output Processors
|
|
211
|
+
|
|
212
|
+
```text
|
|
213
|
+
[Your outputProcessors] → [Memory Processors]
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
1. **Your output processors run FIRST**: guardrails, filters, validators
|
|
217
|
+
2. **Memory processors run AFTER**: `SemanticRecall` (embeddings), `MessageHistory` (persistence)
|
|
218
|
+
|
|
219
|
+
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**.
|
|
220
|
+
|
|
221
|
+
## Guardrails and memory
|
|
222
|
+
|
|
223
|
+
The default execution order provides safe guardrail behavior:
|
|
224
|
+
|
|
225
|
+
### Output guardrails (recommended)
|
|
226
|
+
|
|
227
|
+
Output guardrails run **before** memory processors save messages. If a guardrail aborts:
|
|
228
|
+
|
|
229
|
+
- The tripwire is triggered
|
|
230
|
+
- Memory processors are skipped
|
|
231
|
+
- **No messages are persisted to storage**
|
|
232
|
+
|
|
233
|
+
```typescript
|
|
234
|
+
import { Agent } from '@mastra/core/agent'
|
|
235
|
+
import { Memory } from '@mastra/memory'
|
|
236
|
+
import { openai } from '@ai-sdk/openai'
|
|
237
|
+
|
|
238
|
+
// Output guardrail that blocks inappropriate content
|
|
239
|
+
const contentBlocker = {
|
|
240
|
+
id: 'content-blocker',
|
|
241
|
+
processOutputResult: async ({ messages, abort }) => {
|
|
242
|
+
const hasInappropriateContent = messages.some(msg => containsBadContent(msg))
|
|
243
|
+
if (hasInappropriateContent) {
|
|
244
|
+
abort('Content blocked by guardrail')
|
|
245
|
+
}
|
|
246
|
+
return messages
|
|
247
|
+
},
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const agent = new Agent({
|
|
251
|
+
name: 'safe-agent',
|
|
252
|
+
instructions: 'You are a helpful assistant',
|
|
253
|
+
model: 'openai/gpt-5.4',
|
|
254
|
+
memory: new Memory({ lastMessages: 10 }),
|
|
255
|
+
// Your guardrail runs BEFORE memory saves
|
|
256
|
+
outputProcessors: [contentBlocker],
|
|
257
|
+
})
|
|
258
|
+
|
|
259
|
+
// If the guardrail aborts, nothing is saved to memory
|
|
260
|
+
const result = await agent.generate('Hello')
|
|
261
|
+
if (result.tripwire) {
|
|
262
|
+
console.log('Blocked:', result.tripwire.reason)
|
|
263
|
+
// Memory is empty - no messages were persisted
|
|
264
|
+
}
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
### Input guardrails
|
|
268
|
+
|
|
269
|
+
Input guardrails run **after** memory processors load history. If a guardrail aborts:
|
|
270
|
+
|
|
271
|
+
- The tripwire is triggered
|
|
272
|
+
- The LLM is never called
|
|
273
|
+
- Output processors (including memory persistence) are skipped
|
|
274
|
+
- **No messages are persisted to storage**
|
|
275
|
+
|
|
276
|
+
```typescript
|
|
277
|
+
// Input guardrail that validates user input
|
|
278
|
+
const inputValidator = {
|
|
279
|
+
id: 'input-validator',
|
|
280
|
+
processInput: async ({ messages, abort }) => {
|
|
281
|
+
const lastUserMessage = messages.findLast(m => m.role === 'user')
|
|
282
|
+
if (isInvalidInput(lastUserMessage)) {
|
|
283
|
+
abort('Invalid input detected')
|
|
284
|
+
}
|
|
285
|
+
return messages
|
|
286
|
+
},
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const agent = new Agent({
|
|
290
|
+
name: 'validated-agent',
|
|
291
|
+
instructions: 'You are a helpful assistant',
|
|
292
|
+
model: 'openai/gpt-5.4',
|
|
293
|
+
memory: new Memory({ lastMessages: 10 }),
|
|
294
|
+
// Your guardrail runs AFTER memory loads history
|
|
295
|
+
inputProcessors: [inputValidator],
|
|
296
|
+
})
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
### Summary
|
|
300
|
+
|
|
301
|
+
| Guardrail Type | When it runs | If it aborts |
|
|
302
|
+
| -------------- | -------------------------- | ----------------------------- |
|
|
303
|
+
| Input | After memory loads history | LLM not called, nothing saved |
|
|
304
|
+
| Output | Before memory saves | Nothing saved to storage |
|
|
305
|
+
|
|
306
|
+
Both scenarios are safe - guardrails prevent inappropriate content from being persisted to memory
|
|
307
|
+
|
|
308
|
+
## Related documentation
|
|
309
|
+
|
|
310
|
+
- [Processors](https://mastra.ai/docs/agents/processors) - General processor concepts and custom processor creation
|
|
311
|
+
- [Guardrails](https://mastra.ai/docs/agents/guardrails) - Security and validation processors
|
|
312
|
+
- [Memory Overview](https://mastra.ai/docs/memory/overview) - Memory types and configuration
|
|
313
|
+
|
|
314
|
+
When creating custom processors avoid mutating the input `messages` array or its objects directly.
|