@mastra/libsql 0.0.0-knowledge-org-scope-20260902233451 → 0.0.0-knowledge-w2-20261007195847
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/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/docs/references/docs-agents-human-in-the-loop.md +42 -1
- package/dist/docs/references/docs-deployment-workers.md +13 -3
- package/dist/docs/references/docs-memory-memory-processors.md +7 -1
- package/dist/docs/references/docs-memory-message-history.md +68 -4
- package/dist/docs/references/docs-memory-multi-user-threads.md +1 -1
- package/dist/docs/references/docs-memory-overview.md +6 -6
- package/dist/docs/references/docs-memory-semantic-recall.md +35 -1
- package/dist/docs/references/docs-storage.md +2 -0
- package/dist/docs/references/integrations-channels-github.md +6 -2
- package/dist/docs/references/reference-core-mastra-class.md +3 -1
- package/dist/docs/references/reference-file-based-agents-memory.md +0 -2
- package/dist/docs/references/reference-file-based-agents-storage.md +0 -2
- package/dist/docs/references/reference-memory-memory-class.md +7 -2
- package/dist/docs/references/reference-storage-retention.md +64 -10
- package/dist/index.cjs +3131 -1201
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +3132 -1202
- package/dist/index.js.map +1 -1
- package/dist/shared/single-connection-client.d.ts +29 -0
- package/dist/shared/single-connection-client.d.ts.map +1 -0
- package/dist/storage/db/index.d.ts +7 -4
- package/dist/storage/db/index.d.ts.map +1 -1
- package/dist/storage/db/write-lock.d.ts.map +1 -1
- package/dist/storage/domains/background-tasks/index.d.ts +2 -4
- package/dist/storage/domains/background-tasks/index.d.ts.map +1 -1
- package/dist/storage/domains/datasets/index.d.ts +2 -1
- package/dist/storage/domains/datasets/index.d.ts.map +1 -1
- package/dist/storage/domains/experiments/index.d.ts.map +1 -1
- package/dist/storage/domains/knowledge/index.d.ts +134 -21
- package/dist/storage/domains/knowledge/index.d.ts.map +1 -1
- package/dist/storage/domains/memory/index.d.ts +15 -2
- package/dist/storage/domains/memory/index.d.ts.map +1 -1
- package/dist/storage/domains/notifications/index.d.ts +6 -1
- package/dist/storage/domains/notifications/index.d.ts.map +1 -1
- package/dist/storage/domains/observability/index.d.ts.map +1 -1
- package/dist/storage/domains/schedules/index.d.ts +2 -2
- package/dist/storage/domains/schedules/index.d.ts.map +1 -1
- package/dist/storage/domains/skills/index.d.ts.map +1 -1
- package/dist/storage/domains/workflows/index.d.ts +1 -1
- package/dist/storage/domains/workflows/index.d.ts.map +1 -1
- package/dist/storage/factory-storage.d.ts.map +1 -1
- package/dist/storage/index.d.ts.map +1 -1
- package/dist/storage/retention.d.ts +5 -56
- package/dist/storage/retention.d.ts.map +1 -1
- package/dist/vector/index.d.ts.map +1 -1
- package/dist/vector/write-lock.d.ts +25 -0
- package/dist/vector/write-lock.d.ts.map +1 -1
- package/package.json +13 -11
package/dist/docs/SKILL.md
CHANGED
|
@@ -3,7 +3,7 @@ name: mastra-libsql
|
|
|
3
3
|
description: Documentation for @mastra/libsql. Use when working with @mastra/libsql APIs, configuration, or implementation.
|
|
4
4
|
metadata:
|
|
5
5
|
package: "@mastra/libsql"
|
|
6
|
-
version: "0.0.0-knowledge-
|
|
6
|
+
version: "0.0.0-knowledge-w2-20261007195847"
|
|
7
7
|
---
|
|
8
8
|
|
|
9
9
|
## When to use
|
|
@@ -116,7 +116,44 @@ const stream = await agent.stream('Clean up old records', {
|
|
|
116
116
|
})
|
|
117
117
|
```
|
|
118
118
|
|
|
119
|
-
|
|
119
|
+
The function can be asynchronous. For decisions that depend on the tool name and arguments, use a [classifier](https://mastra.ai/reference/classifier/classifier) to estimate whether the call needs human review:
|
|
120
|
+
|
|
121
|
+
```typescript
|
|
122
|
+
import { Classifier } from '@mastra/core/classifier'
|
|
123
|
+
import { typeSafeAi } from '@ai-sdk/typesafe-ai'
|
|
124
|
+
import { agent } from './agent'
|
|
125
|
+
|
|
126
|
+
const approvalClassifier = new Classifier({
|
|
127
|
+
id: 'tool-approval-classifier',
|
|
128
|
+
model: typeSafeAi.evaluationModel('jev-latest'),
|
|
129
|
+
questions: {
|
|
130
|
+
requiresApproval: {
|
|
131
|
+
type: 'boolean',
|
|
132
|
+
instructions:
|
|
133
|
+
'Does this tool call need human approval because it is destructive, irreversible, expensive, or handles sensitive data?',
|
|
134
|
+
},
|
|
135
|
+
},
|
|
136
|
+
})
|
|
137
|
+
|
|
138
|
+
const stream = await agent.stream('Clean up old records', {
|
|
139
|
+
requireToolApproval: async ({ toolName, args }) => {
|
|
140
|
+
const result = await approvalClassifier.evaluate({
|
|
141
|
+
state: {
|
|
142
|
+
toolName,
|
|
143
|
+
argumentNames: Object.keys(args),
|
|
144
|
+
},
|
|
145
|
+
})
|
|
146
|
+
|
|
147
|
+
return result.answers.requiresApproval.probability >= 0.7
|
|
148
|
+
},
|
|
149
|
+
})
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
The example sends argument names rather than values because the classifier forwards its state to the configured evaluation model. If the decision requires argument values, redact sensitive data first or use an evaluation model and provider that meet the protected tool's data-handling requirements.
|
|
153
|
+
|
|
154
|
+
Returning `true` pauses the tool call for human approval. It doesn't approve or decline the call automatically. Choose a threshold that matches the risk of the tools available to the agent. If this `requireToolApproval` function throws, it defaults to requiring approval.
|
|
155
|
+
|
|
156
|
+
The runtime then combines that result with the tool's `requireApproval` setting. A boolean `true` requires approval, while `false` doesn't disable approval required by `requireToolApproval`. A tool-level `requireApproval` function is authoritative and replaces the combined result for that tool.
|
|
120
157
|
|
|
121
158
|
> **Note:** Function-based `requireToolApproval` is only available on regular `stream()` / `generate()` calls. Durable agents and stored agents persist their options, and a function can't be serialized, so they accept only a boolean. If you pass a function in those contexts it falls back to requiring approval for every tool call.
|
|
122
159
|
|
|
@@ -370,6 +407,10 @@ const handleResume = async () => {
|
|
|
370
407
|
}
|
|
371
408
|
```
|
|
372
409
|
|
|
410
|
+
When a suspended or approval-gated tool call resumes, the stream emits a `tool-call-resumed` chunk with the same `toolCallId` before the call's `tool-result`. Its `payload.kind` is `'suspension'` or `'approval'`, and the payload repeats the original `args`, `suspendPayload`, and `resumeSchema`. The chunk is only emitted when a real suspension or approval request is cleared.
|
|
411
|
+
|
|
412
|
+
With `@mastra/ai-sdk`, it arrives as a `data-tool-call-suspended` part (or `data-tool-call-approval` part for approvals) with `resumed: true`, which replaces the original part and keeps its payload. Use this signal to mark a question as answered. Don't infer it from the shape of the tool output: when the suspension came from a sub-agent, the output of the delegation call is the sub-agent's result, not your answer.
|
|
413
|
+
|
|
373
414
|
## Automatic tool resumption
|
|
374
415
|
|
|
375
416
|
When using tools that call `suspend()`, you can enable automatic resumption so the agent resumes suspended tools based on the user's next message. Set `autoResumeSuspendedTools` to `true` in the agent's default options or per-request:
|
|
@@ -35,7 +35,10 @@ The orchestration worker requires a PubSub backend that supports pull mode (e.g.
|
|
|
35
35
|
|
|
36
36
|
### Scheduler worker
|
|
37
37
|
|
|
38
|
-
Polls storage for due cron schedules and publishes `workflow.start`
|
|
38
|
+
Polls storage for due cron schedules and publishes a `workflow.start` event for each fire. It's a producer only, meaning it creates work for the orchestration worker to pick up:
|
|
39
|
+
|
|
40
|
+
- **Split processes**: Scheduled workflows run on the evented engine, and the orchestration worker runs each fire step by step.
|
|
41
|
+
- **In-process mode**: Scheduled workflows run on the default engine. The orchestration worker in the same process runs each fire in-process, the same way a direct `run.start()` does.
|
|
39
42
|
|
|
40
43
|
The scheduler reads declarative `schedule` fields from your workflow definitions automatically. See [Scheduled workflows](https://mastra.ai/docs/workflows/scheduled-workflows) for how to declare schedules.
|
|
41
44
|
|
|
@@ -57,7 +60,7 @@ The background task worker manages concurrency limits, task lifecycle, and resul
|
|
|
57
60
|
|
|
58
61
|
### In-process mode (default)
|
|
59
62
|
|
|
60
|
-
With no configuration, Mastra
|
|
63
|
+
With no configuration, Mastra runs workers inside the API process. Events flow through an in-memory PubSub, and everything shares a single Node.js runtime.
|
|
61
64
|
|
|
62
65
|
```typescript
|
|
63
66
|
import { Mastra } from '@mastra/core/mastra'
|
|
@@ -68,6 +71,8 @@ export const mastra = new Mastra({
|
|
|
68
71
|
})
|
|
69
72
|
```
|
|
70
73
|
|
|
74
|
+
The server generated by `mastra build` starts these workers automatically. If you use a [server adapter](https://mastra.ai/docs/server/server-adapters) instead, add a call to `mastra.startWorkers()` after your server starts listening. See [Start background workers](https://mastra.ai/docs/server/server-adapters).
|
|
75
|
+
|
|
71
76
|
This setup needs no external infrastructure beyond your storage adapter. It doesn't survive process crashes, and you can't scale individual components.
|
|
72
77
|
|
|
73
78
|
### Split processes
|
|
@@ -132,6 +137,8 @@ You can also pass a worker name to the CLI. The command sets `MASTRA_WORKERS` in
|
|
|
132
137
|
mastra worker start orchestration
|
|
133
138
|
```
|
|
134
139
|
|
|
140
|
+
Set `MASTRA_WORKERS` on every process in a split deployment, including `false` on the API process. Any value switches workflows that declare `schedule` to the evented engine, and every process must run those workflows on the same engine. See [Scheduled workflows](https://mastra.ai/docs/workflows/scheduled-workflows). `mastra worker start` without a worker name doesn't set `MASTRA_WORKERS`, so pass a name or set the variable in the process environment.
|
|
141
|
+
|
|
135
142
|
## Network architecture
|
|
136
143
|
|
|
137
144
|
Workers are internal infrastructure. They're not exposed to end users and don't need their own subdomain or public URL, including an inbound HTTP route.
|
|
@@ -142,7 +149,7 @@ In a split deployment:
|
|
|
142
149
|
- **Workers connect outbound only**: They pull events from the distributed PubSub backend and read/write to the shared storage database. They don't accept inbound traffic from clients.
|
|
143
150
|
- **The orchestration worker calls the API internally**: It sends step execution requests to the API over the container network using `MASTRA_STEP_EXECUTION_URL`. This is internal service-to-service communication, not a public endpoint.
|
|
144
151
|
|
|
145
|
-
All three worker types (orchestration, scheduler, background task) sit behind the API on a private network. They share access to the PubSub backend and storage database but never receive traffic directly from clients. HTTP routes for worker-related features run on the API server rather than the worker process. One example is token
|
|
152
|
+
All three worker types (orchestration, scheduler, background task) sit behind the API on a private network. They share access to the PubSub backend and storage database but never receive traffic directly from clients. HTTP routes for worker-related features run on the API server rather than the worker process. One example is creating a token for a voice integration.
|
|
146
153
|
|
|
147
154
|
## Deploy split workers
|
|
148
155
|
|
|
@@ -285,6 +292,8 @@ curl http://localhost:4111/api/agents
|
|
|
285
292
|
|
|
286
293
|
### Kubernetes
|
|
287
294
|
|
|
295
|
+
> **Helm:** On Kubernetes, the [`mastra-projects` Helm chart](https://mastra.ai/integrations/deploy/kubernetes-helm) renders these deployments for you, with the workers on the same image and environment as the server. It also refuses to install combinations that would run every worker twice. The manifests below are for writing them by hand.
|
|
296
|
+
|
|
288
297
|
Create separate Deployments for the API, orchestration worker, scheduler worker, and background task worker. Use the same image and Secret for each Deployment. Set only the role-specific environment variables directly on each container.
|
|
289
298
|
|
|
290
299
|
The orchestration worker Deployment has the following shape:
|
|
@@ -391,4 +400,5 @@ If the API crashes while a step is executing, that work can be lost and the work
|
|
|
391
400
|
- [Workers reference](https://mastra.ai/reference/workers/overview): Details about worker environment variables and types, with a list of supported storage backends
|
|
392
401
|
- [CLI reference](https://mastra.ai/reference/cli/mastra): `mastra worker build` and `mastra worker start`
|
|
393
402
|
- [PubSub](https://mastra.ai/docs/server/pubsub): Event delivery backends
|
|
403
|
+
- [Kubernetes (Helm)](https://mastra.ai/integrations/deploy/kubernetes-helm): Deploy worker roles with the official chart
|
|
394
404
|
- [Scheduled workflows](https://mastra.ai/docs/workflows/scheduled-workflows): Declare cron schedules on workflows
|
|
@@ -14,6 +14,12 @@ Memory processors are [processors](https://mastra.ai/docs/agents/processors) tha
|
|
|
14
14
|
|
|
15
15
|
Mastra automatically adds these processors when memory is enabled:
|
|
16
16
|
|
|
17
|
+
### `MemoryInputFilter`
|
|
18
|
+
|
|
19
|
+
Trims client-echoed history before memory loaders run. For an existing thread, it keeps only the current user turn or new tool results. For an empty thread, it keeps the full initial input and removes provider item metadata from assistant parts that could refer to items that don't exist in storage.
|
|
20
|
+
|
|
21
|
+
This processor runs first so `MessageHistory`, `SemanticRecall`, and Observational Memory receive only the new input they need.
|
|
22
|
+
|
|
17
23
|
### `MessageHistory`
|
|
18
24
|
|
|
19
25
|
Retrieves message history and persists new messages.
|
|
@@ -206,7 +212,7 @@ Understanding the execution order is important when combining guardrails with me
|
|
|
206
212
|
[Memory Processors] → [Your inputProcessors]
|
|
207
213
|
```
|
|
208
214
|
|
|
209
|
-
1. **Memory processors run FIRST**: `WorkingMemory`, `MessageHistory`, `SemanticRecall`
|
|
215
|
+
1. **Memory processors run FIRST**: `MemoryInputFilter`, then `WorkingMemory`, `MessageHistory`, and `SemanticRecall`
|
|
210
216
|
2. **Your input processors run AFTER**: guardrails, filters, validators
|
|
211
217
|
|
|
212
218
|
As a result, memory loads message history before your processors can validate or filter the input.
|
|
@@ -12,7 +12,9 @@ You can also retrieve message history to display past conversations in your UI.
|
|
|
12
12
|
|
|
13
13
|
> **Warning:** When you use memory with a client application, send **only the new message** from the client instead of the full conversation history.
|
|
14
14
|
>
|
|
15
|
-
> Sending the full history is redundant because Mastra loads messages from storage
|
|
15
|
+
> Sending the full history is redundant because Mastra loads messages from storage. 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.
|
|
16
|
+
>
|
|
17
|
+
> 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 the filtering described above. History still loads underneath. Every input message that isn't already stored is saved to the thread, including few-shot examples.
|
|
16
18
|
>
|
|
17
19
|
> For an AI SDK example, see [Using Mastra Memory](https://mastra.ai/integrations/agentic-ui/ai-sdk-ui).
|
|
18
20
|
|
|
@@ -122,6 +124,29 @@ You can use this history in two ways:
|
|
|
122
124
|
- **Automatic inclusion**: Mastra automatically includes recent messages in the context window. The default of 10 messages keeps agents grounded in the conversation. Adjust it with `lastMessages` when needed.
|
|
123
125
|
- [**Manual querying**](#querying): For more control, query threads and messages directly with `recall()`. Use the results to choose which memories enter the context window or to render conversation history in your UI.
|
|
124
126
|
|
|
127
|
+
> **Note:** `lastMessages` counts every stored message, including tool calls, tool results, and [signals](https://mastra.ai/docs/harness/signals) of any kind, so a single turn can add several messages to the count. The window also slides forward on every request: once a thread grows past the limit, the oldest message leaves context on each turn, which changes the start of the prompt and invalidates the provider prompt cache. For long-running conversations, use [Observational Memory](https://mastra.ai/docs/memory/observational-memory), which keeps the prompt prefix stable.
|
|
128
|
+
|
|
129
|
+
### Limit history by tokens
|
|
130
|
+
|
|
131
|
+
Message count is a poor proxy for context size: a tool result can be a few tokens or thousands. Use `messageHistory` to keep recent history within a token budget instead:
|
|
132
|
+
|
|
133
|
+
```typescript
|
|
134
|
+
export const agent = new Agent({
|
|
135
|
+
id: 'test-agent',
|
|
136
|
+
memory: new Memory({
|
|
137
|
+
options: {
|
|
138
|
+
messageHistory: { maxTokens: 8_000, atMaxRemoveTokens: 2_000 },
|
|
139
|
+
},
|
|
140
|
+
}),
|
|
141
|
+
})
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
Mastra counts the complete prompt against `maxTokens`, including remembered history, system instructions, context, and the current turn. When the prompt exceeds the budget, Mastra removes the oldest remembered messages until the prompt is at most `maxTokens - atMaxRemoveTokens`. `atMaxRemoveTokens` defaults to 25% of `maxTokens`. Removing history in chunks keeps the prompt prefix stable across several turns, which helps provider prompt caches stay warm.
|
|
145
|
+
|
|
146
|
+
System messages, context, the current turn's input, and the agent's responses are never trimmed. Linked tool calls and results are removed together. If protected content alone exceeds `maxTokens`, Mastra removes all remembered history but keeps the protected content.
|
|
147
|
+
|
|
148
|
+
Trimmed messages stay in storage. During agent runs, Mastra persists a per-thread boundary so they're excluded from later turns. Setting `messageHistory` without `lastMessages` disables the default 10-message cap. Set both to combine a count cap with a token budget. Set `maxTokens` to `0` to disable message history.
|
|
149
|
+
|
|
125
150
|
> **Tip:** When memory is enabled, [Studio](https://mastra.ai/docs/studio/overview) uses message history to display past conversations in the chat sidebar.
|
|
126
151
|
|
|
127
152
|
## Thread title generation
|
|
@@ -147,6 +172,43 @@ export const supportAgent = new Agent({
|
|
|
147
172
|
|
|
148
173
|
Title generation runs asynchronously after the agent responds and doesn't affect response time.
|
|
149
174
|
|
|
175
|
+
### Streaming the generated title
|
|
176
|
+
|
|
177
|
+
By default title generation runs in the background and the run's stream doesn't wait for it, so HTTP clients only see the title on their next thread fetch. Set `emitEvent: true` to deliver the title on the run's stream instead: the stream waits for the title and emits a transient `data-thread-title` chunk before `finish`.
|
|
178
|
+
|
|
179
|
+
```typescript
|
|
180
|
+
import { Agent } from '@mastra/core/agent'
|
|
181
|
+
import { Memory } from '@mastra/memory'
|
|
182
|
+
|
|
183
|
+
export const supportAgent = new Agent({
|
|
184
|
+
id: 'support-agent',
|
|
185
|
+
name: 'Support agent',
|
|
186
|
+
instructions: 'Answer customer support questions.',
|
|
187
|
+
model: 'openai/gpt-5.6-sol',
|
|
188
|
+
memory: new Memory({
|
|
189
|
+
options: {
|
|
190
|
+
generateTitle: {
|
|
191
|
+
emitEvent: true,
|
|
192
|
+
},
|
|
193
|
+
},
|
|
194
|
+
}),
|
|
195
|
+
})
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
Stream consumers receive the chunk with the persisted title, so a chat UI can rename its thread list entry without polling:
|
|
199
|
+
|
|
200
|
+
```typescript
|
|
201
|
+
for await (const chunk of stream.fullStream) {
|
|
202
|
+
if (chunk.type === 'data-thread-title') {
|
|
203
|
+
renameThreadInSidebar(chunk.data.threadId, chunk.data.title)
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
The chunk is transient: it's delivered to stream consumers but never persisted as part of the conversation's messages. Because the stream waits for the title, `emitEvent` delays the stream's `finish` on the turn that generates the title: the first turn of a thread, or a later turn when `minMessages` sets a higher threshold. Leave it off to keep title generation fully non-blocking.
|
|
209
|
+
|
|
210
|
+
> **Note:** `emitEvent` applies to `stream()` runs. `generate()` returns JSON and can't carry the chunk, so it keeps non-blocking title generation. [Durable and evented agents](https://mastra.ai/docs/harness/durable-agents) don't emit this chunk yet. In all of these cases the title is still generated and persisted.
|
|
211
|
+
|
|
150
212
|
To optimize cost or behavior, provide a smaller [`model`](https://mastra.ai/models) and custom `instructions`:
|
|
151
213
|
|
|
152
214
|
```typescript
|
|
@@ -178,7 +240,7 @@ const agent = mastra.getAgentById('test-agent')
|
|
|
178
240
|
const memory = await agent.getMemory()
|
|
179
241
|
```
|
|
180
242
|
|
|
181
|
-
|
|
243
|
+
Use the `Memory` instance to query stored threads and messages or clone a conversation.
|
|
182
244
|
|
|
183
245
|
## Querying
|
|
184
246
|
|
|
@@ -232,7 +294,7 @@ const thread = await memory.getThreadById({ threadId: 'thread-123' })
|
|
|
232
294
|
|
|
233
295
|
Once you have a thread, use [`recall()`](https://mastra.ai/reference/memory/recall) to retrieve its messages. It supports pagination and [semantic search](https://mastra.ai/docs/memory/semantic-recall), with optional date filtering.
|
|
234
296
|
|
|
235
|
-
|
|
297
|
+
Fetch a thread's history without pagination. Recall hides reminder signals by default; pass `hideSignals: false` to include them, `true` to hide all recognized signals, or an array to omit selected types. See [signal visibility and compatibility](https://mastra.ai/reference/memory/recall) for matching rules and precedence.
|
|
236
298
|
|
|
237
299
|
```typescript
|
|
238
300
|
const { messages } = await memory.recall({
|
|
@@ -343,7 +405,9 @@ const { thread, clonedMessages } = await memory.cloneThread({
|
|
|
343
405
|
|
|
344
406
|
You can filter cloned messages by count or date range and specify custom thread IDs. Utility methods are also available to inspect clone relationships.
|
|
345
407
|
|
|
346
|
-
|
|
408
|
+
If you don't need the copied messages returned, for example when forking a long thread, use `copyThread()`. It never returns message payloads, and on LibSQL and PostgreSQL the rows are copied inside the database. When semantic recall is enabled, the copied messages are still read back in batches to generate embeddings.
|
|
409
|
+
|
|
410
|
+
See [`cloneThread()`](https://mastra.ai/reference/memory/cloneThread), [`copyThread()`](https://mastra.ai/reference/memory/copyThread), and [clone utilities](https://mastra.ai/reference/memory/clone-utilities) for the full API.
|
|
347
411
|
|
|
348
412
|
## Deleting messages
|
|
349
413
|
|
|
@@ -160,7 +160,7 @@ const memory = new Memory({
|
|
|
160
160
|
|
|
161
161
|
OM requires a storage adapter that supports it: `@mastra/libsql`, `@mastra/pg`, `@mastra/mongodb`, or `@mastra/oracledb`.
|
|
162
162
|
|
|
163
|
-
> **Note:** If you switch the Observer to a
|
|
163
|
+
> **Note:** If you switch the Observer to a less capable model and see facts attributed to a generic `User` instead of individual participants, use [`observation.instruction`](https://mastra.ai/reference/memory/observational-memory) to explain how to interpret the `<turn>` tag.
|
|
164
164
|
|
|
165
165
|
### With working memory
|
|
166
166
|
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
# Memory
|
|
6
6
|
|
|
7
|
-
Memory
|
|
7
|
+
Memory gives your agent access to earlier messages and tool results. The agent can use this context to answer follow-up questions and recall information from previous interactions.
|
|
8
8
|
|
|
9
9
|
Mastra agents can be configured to store [message history](https://mastra.ai/docs/memory/message-history). Additionally, you can enable:
|
|
10
10
|
|
|
@@ -153,7 +153,7 @@ To list all threads for a resource, or retrieve a specific thread, [use the memo
|
|
|
153
153
|
|
|
154
154
|
## Observational Memory
|
|
155
155
|
|
|
156
|
-
|
|
156
|
+
Long conversations can fill the context window with raw message history and reduce agent performance. [Observational Memory](https://mastra.ai/docs/memory/observational-memory) uses background agents to compress older messages into observations. This reduces the context used by message history while retaining information for later turns.
|
|
157
157
|
|
|
158
158
|
**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.
|
|
159
159
|
|
|
@@ -176,7 +176,7 @@ See [Observational Memory](https://mastra.ai/docs/memory/observational-memory) f
|
|
|
176
176
|
|
|
177
177
|
## What the model sees
|
|
178
178
|
|
|
179
|
-
|
|
179
|
+
Memory adds context to the system messages or conversation messages sent to the model. Message history is enabled by default. Other memory features contribute context only when configured. The diagram shows where each feature adds its context, and the list below explains what it contributes:
|
|
180
180
|
|
|
181
181
|

|
|
182
182
|
|
|
@@ -202,7 +202,7 @@ Each delegation creates a fresh `threadId` and a deterministic `resourceId` for
|
|
|
202
202
|
|
|
203
203
|
> **Note:** Title generation (`generateTitle`) is a top-level thread concern and **isn't** applied to inherited subagent threads. Because each delegation creates an ephemeral thread that no one sees, running title generation for it would waste an LLM call per delegation. To generate titles for a subagent's own threads, give that subagent its own memory configuration.
|
|
204
204
|
|
|
205
|
-
The supervisor forwards its conversation context to the subagent so it has enough background to complete the task. Only the delegation prompt and the subagent's response are saved
|
|
205
|
+
The supervisor forwards its conversation context to the subagent so it has enough background to complete the task. Only the delegation prompt and the subagent's response are saved. The full parent conversation isn't stored. You can control which messages reach the subagent with the [`messageFilter`](https://mastra.ai/docs/subagents) callback.
|
|
206
206
|
|
|
207
207
|
> **Note:** Subagent resource IDs are always suffixed with the agent name (`{parentResourceId}-{agentName}`). Different subagents under the same supervisor never share a resource ID through delegation.
|
|
208
208
|
|
|
@@ -212,7 +212,7 @@ To go beyond this default isolation, you can share memory between agents by pass
|
|
|
212
212
|
|
|
213
213
|
When you call agents directly (outside the delegation flow), memory sharing is controlled by two identifiers: `resourceId` and `threadId`. Agents that use the same values read and write to the same data. This is useful when agents collaborate on a shared context, for example, a researcher that saves notes and a writer that reads them.
|
|
214
214
|
|
|
215
|
-
**Resource-scoped sharing** is the most common pattern. [Working memory](https://mastra.ai/docs/memory/working-memory) and [semantic recall](https://mastra.ai/docs/memory/semantic-recall) default to `scope: 'resource'`. If two agents share a `resourceId`, they share
|
|
215
|
+
**Resource-scoped sharing** is the most common pattern. [Working memory](https://mastra.ai/docs/memory/working-memory) and [semantic recall](https://mastra.ai/docs/memory/semantic-recall) default to `scope: 'resource'`. If two agents share a `resourceId`, they share working memory and embeddings, even across different threads:
|
|
216
216
|
|
|
217
217
|
```typescript
|
|
218
218
|
// Both agents share the same resource-scoped memory
|
|
@@ -225,7 +225,7 @@ await writer.generate('Write a summary from the research notes.', {
|
|
|
225
225
|
})
|
|
226
226
|
```
|
|
227
227
|
|
|
228
|
-
Because both calls use `resource: 'project-42'`, the writer can access the researcher's
|
|
228
|
+
Because both calls use `resource: 'project-42'`, the writer can access the researcher's working memory. Semantic embeddings are also shared through the resource. Each agent still has its own thread, so message histories stay separate.
|
|
229
229
|
|
|
230
230
|
**Thread-scoped sharing** gives tighter coupling. [Observational Memory](https://mastra.ai/docs/memory/observational-memory) uses `scope: 'thread'` by default. If two agents use the same `resource` and `thread`, they share the full message history. Each agent sees every message the other has written. This is useful when agents need to build on each other's exact outputs.
|
|
231
231
|
|
|
@@ -20,7 +20,7 @@ After getting a response from the LLM, all new messages (user, assistant, and to
|
|
|
20
20
|
|
|
21
21
|
## Quickstart
|
|
22
22
|
|
|
23
|
-
Semantic recall is disabled by default. To enable it, set `semanticRecall: true` in `options` and provide a `vector` store and `embedder
|
|
23
|
+
Semantic recall is disabled by default. To enable it, set `semanticRecall: true` in `options` and provide a `vector` store and an `embedder`. A store that generates embeddings itself, such as MongoDB with Automated Embedding, works without one. See [Server-side embeddings](#server-side-embeddings).
|
|
24
24
|
|
|
25
25
|
**LibSQL**:
|
|
26
26
|
|
|
@@ -242,6 +242,40 @@ const options = {
|
|
|
242
242
|
}
|
|
243
243
|
```
|
|
244
244
|
|
|
245
|
+
## Server-side embeddings
|
|
246
|
+
|
|
247
|
+
Some vector stores generate the embeddings themselves. With one of those, semantic recall runs without an `embedder`: the database embeds each message on write and the search string on arrival. The embedding provider stays out of your application entirely.
|
|
248
|
+
|
|
249
|
+
MongoDB does this through [Automated Embedding](https://mastra.ai/reference/vectors/mongodb): name a Voyage AI model on the vector store and leave the `embedder` out.
|
|
250
|
+
|
|
251
|
+
```typescript
|
|
252
|
+
import { Memory } from '@mastra/memory'
|
|
253
|
+
import { MongoDBStore, MongoDBVector } from '@mastra/mongodb'
|
|
254
|
+
|
|
255
|
+
const memory = new Memory({
|
|
256
|
+
storage: new MongoDBStore({
|
|
257
|
+
id: 'agent-storage',
|
|
258
|
+
uri: process.env.MONGODB_URI,
|
|
259
|
+
dbName: process.env.MONGODB_DB_NAME,
|
|
260
|
+
}),
|
|
261
|
+
vector: new MongoDBVector({
|
|
262
|
+
id: 'agent-vector',
|
|
263
|
+
uri: process.env.MONGODB_URI,
|
|
264
|
+
dbName: process.env.MONGODB_DB_NAME,
|
|
265
|
+
autoEmbed: { model: 'voyage-4' },
|
|
266
|
+
}),
|
|
267
|
+
options: {
|
|
268
|
+
semanticRecall: { topK: 3, messageRange: 2 },
|
|
269
|
+
},
|
|
270
|
+
})
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
Messages are stored as text and MongoDB embeds them, so the model choice and the vector size belong to the index rather than to your application. Recall works the same way through an agent and through [`recall()`](#using-the-recall-method).
|
|
274
|
+
|
|
275
|
+
MongoDB embeds newly written messages in the background. A message saved moments ago may not be recallable immediately.
|
|
276
|
+
|
|
277
|
+
Every other store expects your application to supply the vectors, and keeps requiring an `embedder`. Enabling semantic recall with neither an `embedder` nor a store that embeds server-side raises an error naming both options.
|
|
278
|
+
|
|
245
279
|
## Embedder configuration
|
|
246
280
|
|
|
247
281
|
Semantic recall relies on an [embedding model](https://mastra.ai/reference/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.
|
|
@@ -194,6 +194,7 @@ Each provider page includes installation instructions, configuration parameters,
|
|
|
194
194
|
|
|
195
195
|
- [Aurora DSQL](https://mastra.ai/integrations/databases/aurora-dsql)
|
|
196
196
|
- [ClickHouse](https://mastra.ai/integrations/databases/clickhouse)
|
|
197
|
+
- [ClickHouse Managed Postgres](https://mastra.ai/integrations/databases/clickhouse-managed-postgres)
|
|
197
198
|
- [Cloudflare D1](https://mastra.ai/integrations/databases/cloudflare-d1)
|
|
198
199
|
- [Cloudflare KV](https://mastra.ai/integrations/databases/cloudflare-kv)
|
|
199
200
|
- [Convex](https://mastra.ai/integrations/databases/convex)
|
|
@@ -205,6 +206,7 @@ Each provider page includes installation instructions, configuration parameters,
|
|
|
205
206
|
- [libSQL](https://mastra.ai/integrations/databases/libsql)
|
|
206
207
|
- [Mastra](https://mastra.ai/docs/mastra-platform/database)
|
|
207
208
|
- [MongoDB](https://mastra.ai/integrations/databases/mongodb)
|
|
209
|
+
- [MySQL](https://mastra.ai/integrations/databases/mysql)
|
|
208
210
|
- [MSSQL](https://mastra.ai/integrations/databases/mssql)
|
|
209
211
|
- [Neon Postgres](https://mastra.ai/integrations/databases/neon)
|
|
210
212
|
- [OracleDB](https://mastra.ai/integrations/databases/oracledb)
|
|
@@ -41,9 +41,13 @@ GitHub Signals requires:
|
|
|
41
41
|
- A Mastra storage adapter with memory and notification support. The provider stores each subscription in the thread's metadata, so the thread must already exist.
|
|
42
42
|
- The `gitcrawl` command on `PATH`, configured to access the repositories you want to monitor. The provider runs `gitcrawl sync` and reads its SQLite database.
|
|
43
43
|
- The `sqlite3` command on `PATH`.
|
|
44
|
-
- The [GitHub CLI](https://cli.github.com/) installed and authenticated. The provider uses `gh api` to check
|
|
44
|
+
- The [GitHub CLI](https://cli.github.com/) installed and authenticated. The provider uses real `gh api` responses to check repository permissions and GitHub App ownership before notifying the agent.
|
|
45
45
|
|
|
46
|
-
By default, comments from users with `admin`, `maintain`, or `write` access can trigger notifications. CodeRabbit and Devin bot comments are
|
|
46
|
+
By default, comments from users with `admin`, `maintain`, or `write` access can trigger notifications. CodeRabbit and Devin bot comments are explicitly allowed.
|
|
47
|
+
|
|
48
|
+
Bot authorization checks `ignoredBots` first, using an exact case-insensitive login match. Other bots can trigger notifications when they appear in `authorizedBots`, when the GitHub App is owned by a user whose repository permission appears in `authorizedPermissions`, or when the app is owned by the organization that owns the repository. The default authorized permissions are `admin`, `maintain`, and `write`.
|
|
49
|
+
|
|
50
|
+
Failed, inaccessible, malformed, and unsupported app-owner lookups deny the bot comment. Successful app-owner lookups are cached for 24 hours; failed lookups aren't cached.
|
|
47
51
|
|
|
48
52
|
## Agent and subscription
|
|
49
53
|
|
|
@@ -85,6 +85,8 @@ Visit the [Configuration reference](https://mastra.ai/reference/configuration) f
|
|
|
85
85
|
|
|
86
86
|
**scorers** (`Record<string, Scorer>`): Scorers for evaluating agent responses and workflow outputs. Registration also makes a scorer resolvable by ID, which is required to persist its scores. See Score persistence (Default: `{}`)
|
|
87
87
|
|
|
88
|
+
**classifiers** (`Record<string, Classifier>`): Classifiers for typed fixed-option evaluation. Registered classifiers can be retrieved by key or ID. See Classifier (Default: `{}`)
|
|
89
|
+
|
|
88
90
|
**processors** (`Record<string, Processor>`): Input/output processors for transforming agent inputs and outputs (Default: `{}`)
|
|
89
91
|
|
|
90
92
|
**gateways** (`Record<string, MastraModelGateway>`): Custom model gateways to register for accessing AI models through alternative providers or private deployments. Structured as a key-value pair, with keys being the registry key (used for getGateway()) and values being gateway instances. (Default: `{}`)
|
|
@@ -131,7 +133,7 @@ Visit the [Configuration reference](https://mastra.ai/reference/configuration) f
|
|
|
131
133
|
|
|
132
134
|
**recovery** (`MastraRecoveryConfig`): Boot-time recovery behavior for orphaned agent and workflow runs. See Crash recovery. (Default: `{ durableAgents: 'off' }`)
|
|
133
135
|
|
|
134
|
-
**recovery.durableAgents** (`'auto' | 'off'`): Set to 'auto' to automatically re-drive orphaned RUNNING durable agent runs on server boot. Recovery re-issues LLM calls and re-executes tool calls, so tools must be idempotent. See Crash recovery.
|
|
136
|
+
**recovery.durableAgents** (`'auto' | 'off'`): Set to 'auto' to automatically re-drive orphaned RUNNING durable agent runs on server boot. This also controls the default snapshot-persistence policy for durable agents: running checkpoints are only written when set to 'auto' (or when an agent sets a custom shouldPersistSnapshot that includes running). Recovery re-issues LLM calls and re-executes tool calls, so tools must be idempotent. See Crash recovery.
|
|
135
137
|
|
|
136
138
|
## Methods
|
|
137
139
|
|
|
@@ -4,8 +4,6 @@
|
|
|
4
4
|
|
|
5
5
|
# Memory
|
|
6
6
|
|
|
7
|
-
> **Beta:** Breaking changes may occur without a major version bump until the API is stable.
|
|
8
|
-
|
|
9
7
|
A file-based agent gets [memory](https://mastra.ai/docs/memory/overview) from a `memory.ts` file that default-exports a [`Memory`](https://mastra.ai/reference/memory/memory-class) instance. Use this page for the file-based convention; use the memory docs for message history, semantic recall, storage, and processors.
|
|
10
8
|
|
|
11
9
|
Without `memory.ts` or `config.memory`, the agent has no memory by default. Each `generate()` or `stream()` call starts without remembered conversation state unless you pass the prior context yourself.
|
|
@@ -4,8 +4,6 @@
|
|
|
4
4
|
|
|
5
5
|
# Storage
|
|
6
6
|
|
|
7
|
-
> **Beta:** Breaking changes may occur without a major version bump until the API is stable.
|
|
8
|
-
|
|
9
7
|
Mastra sets the project's default [storage](https://mastra.ai/docs/storage) from a `storage.ts` file directly under `src/mastra/`. The file default-exports a store, which replaces the built-in in-memory store used for memory, workflows, observability, and other storage domains.
|
|
10
8
|
|
|
11
9
|
Use this page for the file-based convention. For backend choice, storage domains, retention, and provider details, see [storage overview](https://mastra.ai/docs/storage).
|
|
@@ -39,17 +39,21 @@ export const agent = new Agent({
|
|
|
39
39
|
|
|
40
40
|
**options** (`MemoryConfig`): Memory configuration options.
|
|
41
41
|
|
|
42
|
-
**options.lastMessages** (`number | false`): Number of most recent messages to include in context. Set to false to disable the message history feature entirely (messages are not loaded into context or saved). Use Number.MAX\_SAFE\_INTEGER to retrieve all messages with no limit. To load messages without saving new ones, use the readOnly option.
|
|
42
|
+
**options.lastMessages** (`number | false`): Number of most recent messages to include in context. Set to false to disable the message history feature entirely (messages are not loaded into context or saved). Use Number.MAX\_SAFE\_INTEGER to retrieve all messages with no limit. To load messages without saving new ones, use the readOnly option. The window slides forward on every request, so once a thread exceeds the limit, each turn invalidates the provider prompt cache. For long-running conversations, use Observational Memory instead.
|
|
43
|
+
|
|
44
|
+
**options.messageHistory** (`{ maxTokens: number; atMaxRemoveTokens?: number }`): Token budget for the complete prompt, including remembered history, system instructions, context, and the current turn. When the prompt exceeds maxTokens, the oldest remembered messages are dropped until the prompt is at most maxTokens - atMaxRemoveTokens (defaults to 25% of maxTokens). Protected content is never removed. Linked tool calls and results are removed together. During agent runs, trimmed history is excluded from later turns via a persisted per-thread boundary, but the messages themselves stay in storage. When set without an explicit lastMessages, the default 10-message cap is not applied. Set maxTokens to 0 to disable message history. Prefer this over lastMessages, since message count is a poor proxy for context size.
|
|
43
45
|
|
|
44
46
|
**options.readOnly** (`boolean`): When true, prevents memory from saving new messages and provides working memory as read-only context (without the updateWorkingMemory tool). Useful for read-only operations like previews, internal routing agents, or sub agents that should reference but not modify memory.
|
|
45
47
|
|
|
48
|
+
**options.retainFullInput** (`boolean`): When true, the request input is processed exactly as supplied instead of being filtered against stored history. Use this when you assemble the input yourself and need the message sequence preserved. Stored history is still loaded underneath, and every input message that isn't already stored is saved to the thread, including few-shot examples. Can be set per call on memory.options or agent-wide in the memory constructor options.
|
|
49
|
+
|
|
46
50
|
**options.semanticRecall** (`boolean | { topK: number; messageRange: number | { before: number; after: number }; scope?: 'thread' | 'resource' }`): Enable semantic search in message history. Can be a boolean or an object with configuration options. When enabled, requires both vector store and embedder to be configured. Default topK is 4, default messageRange is {before: 1, after: 1}.
|
|
47
51
|
|
|
48
52
|
**options.workingMemory** (`WorkingMemory`): Configuration for working memory feature. Can be { enabled: boolean; template?: string; schema?: ZodObject\<any> | JSONSchema7; scope?: 'thread' | 'resource' } or { enabled: boolean } to disable.
|
|
49
53
|
|
|
50
54
|
**options.observationalMemory** (`boolean | ObservationalMemoryOptions`): Enable Observational Memory for long-context agentic memory. Set to true for defaults, or pass a config object to customize token budgets, models, and scope. See Observational Memory reference for configuration details.
|
|
51
55
|
|
|
52
|
-
**options.generateTitle** (`boolean | { model
|
|
56
|
+
**options.generateTitle** (`boolean | { model?: DynamicArgument<MastraModelConfig>; instructions?: DynamicArgument<string>; minMessages?: number; emitEvent?: boolean }`): Controls automatic thread title generation from the conversation transcript. Accepts a boolean or an object with a custom model (any MastraModelConfig: a model instance, a "provider/model" ID, or an OpenAI-compatible config; defaults to the agent's own model), custom instructions, a minimum message count, and emitEvent. With emitEvent: true the run's stream waits for the title and emits it as a transient data-thread-title chunk before finish (durable and evented agents persist the title but don't emit the chunk yet).
|
|
53
57
|
|
|
54
58
|
## Returns
|
|
55
59
|
|
|
@@ -147,5 +151,6 @@ export const agent = new Agent({
|
|
|
147
151
|
- [listThreads](https://mastra.ai/reference/memory/listThreads)
|
|
148
152
|
- [deleteMessages](https://mastra.ai/reference/memory/deleteMessages)
|
|
149
153
|
- [cloneThread](https://mastra.ai/reference/memory/cloneThread)
|
|
154
|
+
- [copyThread](https://mastra.ai/reference/memory/copyThread)
|
|
150
155
|
- [settled](https://mastra.ai/reference/memory/settled)
|
|
151
156
|
- [Clone Utility Methods](https://mastra.ai/reference/memory/clone-utilities)
|