@mastra/libsql 0.0.0-error-handler-fix-20251020202607 → 0.0.0-esbuild-bundle-worker-20260807182016

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 (104) hide show
  1. package/CHANGELOG.md +4789 -3
  2. package/LICENSE.md +15 -0
  3. package/README.md +30 -20
  4. package/dist/docs/SKILL.md +52 -0
  5. package/dist/docs/assets/SOURCE_MAP.json +6 -0
  6. package/dist/docs/references/docs-agents-agent-approval.md +664 -0
  7. package/dist/docs/references/docs-agents-networks.md +184 -0
  8. package/dist/docs/references/docs-deployment-workers.md +137 -0
  9. package/dist/docs/references/docs-editor-overview.md +349 -0
  10. package/dist/docs/references/docs-memory-memory-processors.md +385 -0
  11. package/dist/docs/references/docs-memory-message-history.md +348 -0
  12. package/dist/docs/references/docs-memory-multi-user-threads.md +208 -0
  13. package/dist/docs/references/docs-memory-overview.md +266 -0
  14. package/dist/docs/references/docs-memory-semantic-recall.md +401 -0
  15. package/dist/docs/references/docs-memory-working-memory.md +431 -0
  16. package/dist/docs/references/docs-storage-overview.md +214 -0
  17. package/dist/docs/references/docs-workflows-snapshots.md +240 -0
  18. package/dist/docs/references/guides-agent-frameworks-ai-sdk.md +142 -0
  19. package/dist/docs/references/guides-rag-retrieval.md +520 -0
  20. package/dist/docs/references/reference-core-getMemory.md +51 -0
  21. package/dist/docs/references/reference-core-listMemory.md +57 -0
  22. package/dist/docs/references/reference-core-mastra-class.md +153 -0
  23. package/dist/docs/references/reference-file-based-agents-memory.md +58 -0
  24. package/dist/docs/references/reference-file-based-agents-storage.md +30 -0
  25. package/dist/docs/references/reference-memory-memory-class.md +148 -0
  26. package/dist/docs/references/reference-storage-composite.md +397 -0
  27. package/dist/docs/references/reference-storage-dynamodb.md +284 -0
  28. package/dist/docs/references/reference-storage-libsql.md +143 -0
  29. package/dist/docs/references/reference-storage-retention.md +248 -0
  30. package/dist/docs/references/reference-vectors-libsql.md +307 -0
  31. package/dist/index.cjs +13164 -3390
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.js +13134 -3383
  34. package/dist/index.js.map +1 -1
  35. package/dist/storage/db/index.d.ts +389 -0
  36. package/dist/storage/db/index.d.ts.map +1 -0
  37. package/dist/storage/db/utils.d.ts +84 -0
  38. package/dist/storage/db/utils.d.ts.map +1 -0
  39. package/dist/storage/db/write-lock.d.ts +8 -0
  40. package/dist/storage/db/write-lock.d.ts.map +1 -0
  41. package/dist/storage/domains/agents/index.d.ts +30 -0
  42. package/dist/storage/domains/agents/index.d.ts.map +1 -0
  43. package/dist/storage/domains/background-tasks/index.d.ts +27 -0
  44. package/dist/storage/domains/background-tasks/index.d.ts.map +1 -0
  45. package/dist/storage/domains/blobs/index.d.ts +17 -0
  46. package/dist/storage/domains/blobs/index.d.ts.map +1 -0
  47. package/dist/storage/domains/channels/index.d.ts +20 -0
  48. package/dist/storage/domains/channels/index.d.ts.map +1 -0
  49. package/dist/storage/domains/datasets/index.d.ts +43 -0
  50. package/dist/storage/domains/datasets/index.d.ts.map +1 -0
  51. package/dist/storage/domains/experiments/index.d.ts +54 -0
  52. package/dist/storage/domains/experiments/index.d.ts.map +1 -0
  53. package/dist/storage/domains/favorites/index.d.ts +17 -0
  54. package/dist/storage/domains/favorites/index.d.ts.map +1 -0
  55. package/dist/storage/domains/harness/index.d.ts +17 -0
  56. package/dist/storage/domains/harness/index.d.ts.map +1 -0
  57. package/dist/storage/domains/mcp-clients/index.d.ts +26 -0
  58. package/dist/storage/domains/mcp-clients/index.d.ts.map +1 -0
  59. package/dist/storage/domains/mcp-servers/index.d.ts +26 -0
  60. package/dist/storage/domains/mcp-servers/index.d.ts.map +1 -0
  61. package/dist/storage/domains/memory/index.d.ts +58 -54
  62. package/dist/storage/domains/memory/index.d.ts.map +1 -1
  63. package/dist/storage/domains/notifications/index.d.ts +23 -0
  64. package/dist/storage/domains/notifications/index.d.ts.map +1 -0
  65. package/dist/storage/domains/observability/index.d.ts +49 -29
  66. package/dist/storage/domains/observability/index.d.ts.map +1 -1
  67. package/dist/storage/domains/prompt-blocks/index.d.ts +25 -0
  68. package/dist/storage/domains/prompt-blocks/index.d.ts.map +1 -0
  69. package/dist/storage/domains/schedules/index.d.ts +27 -0
  70. package/dist/storage/domains/schedules/index.d.ts.map +1 -0
  71. package/dist/storage/domains/scorer-definitions/index.d.ts +26 -0
  72. package/dist/storage/domains/scorer-definitions/index.d.ts.map +1 -0
  73. package/dist/storage/domains/scores/index.d.ts +29 -31
  74. package/dist/storage/domains/scores/index.d.ts.map +1 -1
  75. package/dist/storage/domains/skills/index.d.ts +26 -0
  76. package/dist/storage/domains/skills/index.d.ts.map +1 -0
  77. package/dist/storage/domains/thread-state/index.d.ts +38 -0
  78. package/dist/storage/domains/thread-state/index.d.ts.map +1 -0
  79. package/dist/storage/domains/tool-provider-connections/index.d.ts +14 -0
  80. package/dist/storage/domains/tool-provider-connections/index.d.ts.map +1 -0
  81. package/dist/storage/domains/utils.d.ts +28 -54
  82. package/dist/storage/domains/utils.d.ts.map +1 -1
  83. package/dist/storage/domains/workflow-definitions/index.d.ts +14 -0
  84. package/dist/storage/domains/workflow-definitions/index.d.ts.map +1 -0
  85. package/dist/storage/domains/workflows/index.d.ts +27 -32
  86. package/dist/storage/domains/workflows/index.d.ts.map +1 -1
  87. package/dist/storage/domains/workspaces/index.d.ts +26 -0
  88. package/dist/storage/domains/workspaces/index.d.ts.map +1 -0
  89. package/dist/storage/factory-storage.d.ts +28 -0
  90. package/dist/storage/factory-storage.d.ts.map +1 -0
  91. package/dist/storage/index.d.ts +128 -255
  92. package/dist/storage/index.d.ts.map +1 -1
  93. package/dist/storage/retention.d.ts +77 -0
  94. package/dist/storage/retention.d.ts.map +1 -0
  95. package/dist/vector/index.d.ts +31 -4
  96. package/dist/vector/index.d.ts.map +1 -1
  97. package/dist/vector/sql-builder.d.ts.map +1 -1
  98. package/package.json +22 -16
  99. package/dist/storage/domains/legacy-evals/index.d.ts +0 -18
  100. package/dist/storage/domains/legacy-evals/index.d.ts.map +0 -1
  101. package/dist/storage/domains/operations/index.d.ts +0 -110
  102. package/dist/storage/domains/operations/index.d.ts.map +0 -1
  103. package/dist/storage/domains/traces/index.d.ts +0 -21
  104. package/dist/storage/domains/traces/index.d.ts.map +0 -1
@@ -0,0 +1,431 @@
1
+ > Discover all available pages from the documentation index: https://mastra.ai/llms.txt
2
+
3
+ # Working Memory
4
+
5
+ While [message history](https://mastra.ai/docs/memory/message-history) and [semantic recall](https://mastra.ai/docs/memory/semantic-recall) help agents remember conversations, working memory allows them to maintain persistent information about users across interactions.
6
+
7
+ Working memory is the agent's active scratchpad: key information it keeps available about the user or task. It can retain a person's name, preferences, or other important details during a conversation.
8
+
9
+ This is useful for maintaining ongoing state that's always relevant and should always be available to the agent.
10
+
11
+ If you use [Observational Memory](https://mastra.ai/docs/memory/observational-memory), `observationalMemory.observation.manageWorkingMemory` lets OM update working memory for the agent.
12
+
13
+ > **📹 Watch:** Watch [Mastra working memory](https://www.youtube.com/watch?v=UMy_JHLf1n8\&pp=ygUVbWFzdHJhIHdvcmtpbmcgbWVtb3J5) to see how agents keep persistent user context available across interactions.
14
+
15
+ Working memory can persist at two different scopes:
16
+
17
+ - **Resource-scoped** (default): Memory persists across all conversation threads for the same user
18
+ - **Thread-scoped**: Memory is isolated per conversation thread
19
+
20
+ **Requirement:** Switching between scopes means the agent won't see memory from the other scope - thread-scoped memory is completely separate from resource-scoped memory.
21
+
22
+ ## Quickstart
23
+
24
+ Here's a minimal example of setting up an agent with working memory:
25
+
26
+ ```typescript
27
+ import { Agent } from '@mastra/core/agent'
28
+ import { Memory } from '@mastra/memory'
29
+
30
+ // Create agent with working memory enabled
31
+ const agent = new Agent({
32
+ id: 'personal-assistant',
33
+ name: 'PersonalAssistant',
34
+ instructions: 'You are a helpful personal assistant.',
35
+ model: 'openai/gpt-5.6-sol',
36
+ memory: new Memory({
37
+ options: {
38
+ workingMemory: {
39
+ enabled: true,
40
+ },
41
+ },
42
+ }),
43
+ })
44
+ ```
45
+
46
+ ## How it works
47
+
48
+ Working memory is a block of Markdown text that the agent can update over time to store continuously relevant information.
49
+
50
+ ## Memory persistence scopes
51
+
52
+ Working memory can operate in two different scopes, allowing you to choose how memory persists across conversations:
53
+
54
+ ### Resource-Scoped Memory (Default)
55
+
56
+ By default, working memory persists across all conversation threads for the same user (resourceId), enabling persistent user memory:
57
+
58
+ ```typescript
59
+ const memory = new Memory({
60
+ storage,
61
+ options: {
62
+ workingMemory: {
63
+ enabled: true,
64
+ scope: 'resource', // Memory persists across all user threads
65
+ template: `# User Profile
66
+ - **Name**:
67
+ - **Location**:
68
+ - **Interests**:
69
+ - **Preferences**:
70
+ - **Long-term Goals**:
71
+ `,
72
+ },
73
+ },
74
+ })
75
+ ```
76
+
77
+ **Use cases:**
78
+
79
+ - Personal assistants that remember user preferences
80
+ - Customer service bots that maintain customer context
81
+ - Educational applications that track student progress
82
+
83
+ ### Usage with Agents
84
+
85
+ When using resource-scoped memory, make sure to pass the `resource` parameter in the memory options:
86
+
87
+ ```typescript
88
+ // Resource-scoped memory requires resource
89
+ const response = await agent.generate('Hello!', {
90
+ memory: {
91
+ thread: 'conversation-123',
92
+ resource: 'user-alice-456', // Same user across different threads
93
+ },
94
+ })
95
+ ```
96
+
97
+ ### Thread-Scoped Memory
98
+
99
+ Thread-scoped memory isolates working memory to individual conversation threads. Each thread maintains its own isolated memory:
100
+
101
+ ```typescript
102
+ const memory = new Memory({
103
+ storage,
104
+ options: {
105
+ workingMemory: {
106
+ enabled: true,
107
+ scope: 'thread', // Memory is isolated per thread
108
+ template: `# User Profile
109
+ - **Name**:
110
+ - **Interests**:
111
+ - **Current Goal**:
112
+ `,
113
+ },
114
+ },
115
+ })
116
+ ```
117
+
118
+ **Use cases:**
119
+
120
+ - Different conversations about separate topics
121
+ - Temporary or session-specific information
122
+ - Workflows where each thread needs working memory but threads are ephemeral and not related to each other
123
+
124
+ ## Storage adapter support
125
+
126
+ Resource-scoped working memory requires specific storage adapters that support the `mastra_resources` table:
127
+
128
+ ### Supported Storage Adapters
129
+
130
+ - **libSQL** (`@mastra/libsql`)
131
+ - **PostgreSQL** (`@mastra/pg`)
132
+ - **Upstash** (`@mastra/upstash`)
133
+ - **MongoDB** (`@mastra/mongodb`)
134
+
135
+ ## Custom templates
136
+
137
+ Templates guide the agent on what information to track and update in working memory. Mastra uses a default template when you don't provide one. Define a custom template for your agent's use case so it remembers the most relevant information. For threads shared by multiple users, see [Multi-user threads](https://mastra.ai/docs/memory/multi-user-threads).
138
+
139
+ Here's an example of a custom template. In this example the agent will store the users name, location, timezone, etc as soon as the user sends a message containing any of the info:
140
+
141
+ ```typescript
142
+ const memory = new Memory({
143
+ options: {
144
+ workingMemory: {
145
+ enabled: true,
146
+ template: `
147
+ # User Profile
148
+
149
+ ## Personal info
150
+
151
+ - Name:
152
+ - Location:
153
+ - Timezone:
154
+
155
+ ## Preferences
156
+
157
+ - Communication Style: [e.g., Formal, Casual]
158
+ - Project Goal:
159
+ - Key Deadlines:
160
+ - [Deadline 1]: [Date]
161
+ - [Deadline 2]: [Date]
162
+
163
+ ## Session state
164
+
165
+ - Last Task Discussed:
166
+ - Open Questions:
167
+ - [Question 1]
168
+ - [Question 2]
169
+ `,
170
+ },
171
+ },
172
+ })
173
+ ```
174
+
175
+ ## Designing effective templates
176
+
177
+ A well-structured template keeps the information straightforward for the agent to parse and update. Treat the template as a short form that you want the assistant to keep up to date.
178
+
179
+ - **Short, focused labels.** Avoid paragraphs or very long headings. Keep labels brief (for example `## Personal Info` or `- Name:`) so updates are readable and less likely to be truncated.
180
+ - **Use consistent casing.** Inconsistent capitalization (`Timezone:` vs `timezone:`) can cause messy updates. Stick to Title Case or lower case for headings and bullet labels.
181
+ - **Keep placeholder text minimal.** Use hints such as `[e.g., Formal]` or `[Date]` to help the LLM fill in the correct spots.
182
+ - **Abbreviate very long values.** If you only need a short form, include guidance like `- Name: [First name or nickname]` or `- Address (short):` rather than the full legal text.
183
+ - **Mention update rules in `instructions`.** You can instruct how and when to fill or clear parts of the template directly in the agent's `instructions` field.
184
+
185
+ ### Alternative Template Styles
186
+
187
+ Use a shorter single block if you only need a few items:
188
+
189
+ ```typescript
190
+ const basicMemory = new Memory({
191
+ options: {
192
+ workingMemory: {
193
+ enabled: true,
194
+ template: `User Facts:\n- Name:\n- Favorite Color:\n- Current Topic:`,
195
+ },
196
+ },
197
+ })
198
+ ```
199
+
200
+ You can also store the key facts in a short paragraph format if you prefer a more narrative style:
201
+
202
+ ```typescript
203
+ const paragraphMemory = new Memory({
204
+ options: {
205
+ workingMemory: {
206
+ enabled: true,
207
+ template: `Important Details:\n\nKeep a short paragraph capturing the user's important facts (name, main goal, current task).`,
208
+ },
209
+ },
210
+ })
211
+ ```
212
+
213
+ ## Structured working memory
214
+
215
+ Working memory can also be defined using a structured schema instead of a Markdown template. This allows you to specify the exact fields and types that should be tracked, using a [Standard JSON Schema](https://standardschema.dev/json-schema) ([Zod](https://zod.dev/), [Valibot](https://valibot.dev/), [ArkType](https://arktype.io/), etc.). When using a schema, the agent will see and update working memory as a JSON object matching your schema.
216
+
217
+ **Requirement:** You must specify either `template` or `schema`, but not both.
218
+
219
+ ### Example: Schema-Based Working Memory
220
+
221
+ ```typescript
222
+ import { z } from 'zod'
223
+ import { Memory } from '@mastra/memory'
224
+
225
+ const userProfileSchema = z.object({
226
+ name: z.string().optional(),
227
+ location: z.string().optional(),
228
+ timezone: z.string().optional(),
229
+ preferences: z
230
+ .object({
231
+ communicationStyle: z.string().optional(),
232
+ projectGoal: z.string().optional(),
233
+ deadlines: z.array(z.string()).optional(),
234
+ })
235
+ .optional(),
236
+ })
237
+
238
+ const memory = new Memory({
239
+ options: {
240
+ workingMemory: {
241
+ enabled: true,
242
+ schema: userProfileSchema,
243
+ // template: ... (do not set)
244
+ },
245
+ },
246
+ })
247
+ ```
248
+
249
+ When a schema is provided, the agent receives the working memory as a JSON object. For example:
250
+
251
+ ```json
252
+ {
253
+ "name": "Sam",
254
+ "location": "Berlin",
255
+ "timezone": "CET",
256
+ "preferences": {
257
+ "communicationStyle": "Formal",
258
+ "projectGoal": "Launch MVP",
259
+ "deadlines": ["2025-07-01"]
260
+ }
261
+ }
262
+ ```
263
+
264
+ ### Merge Semantics for Schema-Based Memory
265
+
266
+ Schema-based working memory uses **merge semantics**, meaning the agent only needs to include fields it wants to add or update. Existing fields are preserved automatically.
267
+
268
+ - **Object fields are deep merged:** Only provided fields are updated; others remain unchanged
269
+ - **Set a field to `null` to delete it:** This explicitly removes the field from memory
270
+ - **Arrays are replaced entirely:** When an array field is provided, it replaces the existing array (arrays aren't merged element-by-element)
271
+
272
+ ## Choosing between template and schema
273
+
274
+ - Use a **template** (Markdown) if you want the agent to maintain memory as a free-form text block, such as a user profile or scratchpad. Templates use **replace semantics**: the agent must provide the complete memory content on each update.
275
+ - Use a **schema** if you need structured, type-safe data that can be validated and programmatically accessed as JSON. The `workingMemory.schema` field accepts any `PublicSchema`-compatible schema (including Zod v3, Zod v4, JSON Schema, or already-standard schemas). Schemas use **merge semantics**: the agent only provides fields to update, and existing fields are preserved.
276
+ - Only one mode can be active at a time: setting both `template` and `schema` isn't supported.
277
+
278
+ ## Example: Multi-step retention
279
+
280
+ Below is a simplified view of how the `User Profile` template updates across a short user conversation:
281
+
282
+ ```nohighlight
283
+ # User Profile
284
+
285
+ ## Personal info
286
+
287
+ - Name:
288
+ - Location:
289
+ - Timezone:
290
+
291
+ --- After user says "My name is **Sam** and I'm from **Berlin**" ---
292
+
293
+ # User Profile
294
+ - Name: Sam
295
+ - Location: Berlin
296
+ - Timezone:
297
+
298
+ --- After user adds "By the way I'm normally in **CET**" ---
299
+
300
+ # User Profile
301
+ - Name: Sam
302
+ - Location: Berlin
303
+ - Timezone: CET
304
+ ```
305
+
306
+ The agent can now refer to `Sam` or `Berlin` in later responses without requesting the information again because it has been stored in working memory.
307
+
308
+ If your agent isn't properly updating working memory when you expect it to, you can add system instructions on _how_ and _when_ to use this template in your agent's `instructions` setting.
309
+
310
+ ## Setting initial working memory
311
+
312
+ While agents typically update working memory through the `updateWorkingMemory` tool, you can also set initial working memory programmatically when creating or updating threads. This is useful for injecting user data (like their name, preferences, or other info) that you want available to the agent without passing it in every request.
313
+
314
+ ### Setting Working Memory via Thread Metadata
315
+
316
+ When creating a thread, you can provide initial working memory through the metadata's `workingMemory` key:
317
+
318
+ ```typescript
319
+ // Create a thread with initial working memory
320
+ const thread = await memory.createThread({
321
+ threadId: 'thread-123',
322
+ resourceId: 'user-456',
323
+ title: 'Medical Consultation',
324
+ metadata: {
325
+ workingMemory: `# Patient Profile
326
+ - Name: John Doe
327
+ - Blood Type: O+
328
+ - Allergies: Penicillin
329
+ - Current Medications: None
330
+ - Medical History: Hypertension (controlled)
331
+ `,
332
+ },
333
+ })
334
+
335
+ // The agent will now have access to this information in all messages
336
+ await agent.generate("What's my blood type?", {
337
+ memory: {
338
+ thread: thread.id,
339
+ resource: 'user-456',
340
+ },
341
+ })
342
+ // Response: "Your blood type is O+."
343
+ ```
344
+
345
+ ### Updating Working Memory Programmatically
346
+
347
+ You can also update an existing thread's working memory:
348
+
349
+ ```typescript
350
+ // Update thread metadata to add/modify working memory
351
+ await memory.updateThread({
352
+ id: 'thread-123',
353
+ title: thread.title,
354
+ metadata: {
355
+ ...thread.metadata,
356
+ workingMemory: `# Patient Profile
357
+ - Name: John Doe
358
+ - Blood Type: O+
359
+ - Allergies: Penicillin, Ibuprofen // Updated
360
+ - Current Medications: Lisinopril 10mg daily // Added
361
+ - Medical History: Hypertension (controlled)
362
+ `,
363
+ },
364
+ })
365
+ ```
366
+
367
+ ### Direct Memory Update
368
+
369
+ Alternatively, use the `updateWorkingMemory` method directly:
370
+
371
+ ```typescript
372
+ await memory.updateWorkingMemory({
373
+ threadId: 'thread-123',
374
+ resourceId: 'user-456', // Required for resource-scoped memory
375
+ workingMemory: 'Updated memory content...',
376
+ })
377
+ ```
378
+
379
+ ## Read-only working memory
380
+
381
+ In some scenarios, you may want an agent to have access to working memory data without the ability to modify it. This is useful for:
382
+
383
+ - **Routing agents** that need context but shouldn't update user profiles
384
+ - **Sub agents** in a multi-agent system that should reference but not own the memory
385
+
386
+ To enable read-only mode, set `readOnly: true` in the memory options:
387
+
388
+ ```typescript
389
+ const response = await agent.generate('What do you know about me?', {
390
+ memory: {
391
+ thread: 'conversation-123',
392
+ resource: 'user-alice-456',
393
+ options: {
394
+ readOnly: true, // Working memory is provided but cannot be updated
395
+ },
396
+ },
397
+ })
398
+ ```
399
+
400
+ ## Opt in to state signals (experimental)
401
+
402
+ By default, working memory reaches the model as part of the system message. You can opt into delivering it as a [state signal](https://mastra.ai/docs/long-running-agents/signals) instead by setting `useStateSignals: true`:
403
+
404
+ ```typescript
405
+ const memory = new Memory({
406
+ storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:./mastra.db' }),
407
+ options: {
408
+ workingMemory: {
409
+ enabled: true,
410
+ template: '# User\n- name:\n- location:',
411
+ useStateSignals: true, // experimental: deliver as state signal
412
+ },
413
+ },
414
+ })
415
+ ```
416
+
417
+ What changes:
418
+
419
+ - **Storage is identical.** The same resource/thread `workingMemory` field is read and written.
420
+ - **The tool is the same shape, exposed under a new name.** Writes still flow through the same underlying tool; on this path it's registered as `setWorkingMemory` (instead of `updateWorkingMemory`). The rename keeps legacy strip filters from removing tool-call parts so they persist as a normal audit trail and the next model step picks the new value up automatically.
421
+ - **Delivery only.** Instead of folding into the system prompt, `Memory` auto-attaches a `WorkingMemoryStateProcessor` that emits the current working memory as a `state` signal with `stateId: 'working-memory'`.
422
+
423
+ You inherit the standard state-signal benefits: thread-scoped tracking metadata, `cacheKey` dedup so identical snapshots are only emitted once, and `contextWindow.hasSnapshot` re-injection when an older snapshot rolls out of the window.
424
+
425
+ The default (`useStateSignals: false`) keeps the existing system-message behavior unchanged. `useStateSignals` isn't supported with template working memory `version: 'vnext'`.
426
+
427
+ ## Examples
428
+
429
+ - [Working memory with template](https://github.com/mastra-ai/mastra/tree/main/examples/memory-with-template)
430
+ - [Working memory with schema](https://github.com/mastra-ai/mastra/tree/main/examples/memory-with-schema)
431
+ - [Per-resource working memory](https://github.com/mastra-ai/mastra/tree/main/examples/memory-per-resource-example): Complete example showing resource-scoped memory persistence
@@ -0,0 +1,214 @@
1
+ > Discover all available pages from the documentation index: https://mastra.ai/llms.txt
2
+
3
+ # Storage overview
4
+
5
+ Storage is the persistence layer for the Mastra runtime. It keeps memory, workflow state, observability data, eval results, schedules, and long-running agent state available after a process restarts.
6
+
7
+ Storage powers:
8
+
9
+ - [Memory](https://mastra.ai/docs/memory/overview): Message history, threads, resources, and working memory.
10
+ - [Workflows](https://mastra.ai/docs/workflows/overview): Durable snapshots for suspended and resumed workflow runs.
11
+ - [Observability](https://mastra.ai/docs/observability/overview): Traces, spans, metrics, logs, and feedback.
12
+ - [Evals](https://mastra.ai/docs/evals/overview): Scores, datasets, experiments, and evaluation results.
13
+ - [Long-running agents](https://mastra.ai/docs/long-running-agents/durable-agents): Background tasks, schedules, goals, and thread state.
14
+
15
+ ## When to configure storage
16
+
17
+ Configure a persistent storage adapter when state must survive restarts or be shared across processes. Persistent storage also keeps state visible in Studio across sessions. The default in-memory store is useful for tests and short local experiments, but it loses data when the process exits.
18
+
19
+ Use storage when your application needs any of these behaviors:
20
+
21
+ - Agents remember past messages or user facts.
22
+ - Workflows suspend and resume after a restart.
23
+ - Traces, metrics, logs, scores, or feedback stay available for analysis.
24
+ - Schedules and background tasks continue across deployments.
25
+ - Multiple runtime processes read and write the same state.
26
+
27
+ ## How storage works
28
+
29
+ Mastra storage is organized into **domains**. A domain owns one type of runtime data, and a storage adapter implements one or more domains.
30
+
31
+ | Domain | What it stores |
32
+ | ----------------- | --------------------------------------------------------------------------- |
33
+ | `memory` | Threads, messages, resources, working memory, and other agent memory state. |
34
+ | `workflows` | Workflow snapshots used to suspend and resume runs. |
35
+ | `observability` | Traces, spans, metrics, logs, and feedback. |
36
+ | `scores` | Eval score records. |
37
+ | `datasets` | Dataset records and dataset items used by evals and experiments. |
38
+ | `experiments` | Experiment runs and per-item experiment results. |
39
+ | `backgroundTasks` | Background task records and execution state. |
40
+ | `schedules` | Schedule definitions and trigger history. |
41
+ | `threadState` | Durable task, goal, and thread state. |
42
+
43
+ Adapter support varies by domain. For the full domain list and built-in schemas, see the [storage overview reference](https://mastra.ai/reference/storage/overview).
44
+
45
+ ## Choose a backend by data shape
46
+
47
+ Different domains write and query different kinds of data. Pick a backend based on the domain's access pattern:
48
+
49
+ - `memory`: Reads and writes rows during every remembered agent call. Use a transactional database such as libSQL, PostgreSQL, or MongoDB.
50
+ - `observability`: Writes high-volume telemetry and often queries aggregations. Use a dedicated observability store or an online analytical processing (OLAP) backend such as ClickHouse or DuckDB.
51
+ - `workflows`: Stores durable snapshots that must be available when a run resumes. Use a reliable persistent database.
52
+ - `scores`, `datasets`, and `experiments`: Store lower-frequency evaluation data that's often read later for analysis.
53
+ - `schedules`: Stores schedule definitions and fire history. Use an adapter that implements the schedules domain.
54
+
55
+ When domains have different operational needs, use [composite storage](#composite-storage) to route each domain to the right backend.
56
+
57
+ ## Get started locally
58
+
59
+ For local development, use libSQL with a file-backed database. It doesn't require a separate database server and persists state between restarts.
60
+
61
+ ```typescript
62
+ import { Mastra } from '@mastra/core'
63
+ import { LibSQLStore } from '@mastra/libsql'
64
+
65
+ export const mastra = new Mastra({
66
+ storage: new LibSQLStore({
67
+ id: 'mastra-storage',
68
+ url: 'file:./mastra.db',
69
+ }),
70
+ })
71
+ ```
72
+
73
+ > **Sharing the database with Studio:** When running `mastra dev` alongside your application, use an absolute path so both processes access the same database:
74
+ >
75
+ > ```typescript
76
+ > url: 'file:/absolute/path/to/your/project/mastra.db'
77
+ > ```
78
+ >
79
+ > Relative paths like `file:./mastra.db` resolve based on each process's working directory, which may differ.
80
+
81
+ Mastra initializes the required storage structures on first use.
82
+
83
+ ## Configure for production
84
+
85
+ For production, use a persistent managed database. PostgreSQL is a good default for most teams because it works well for transactional runtime state and is widely available as a managed service.
86
+
87
+ Production guidance:
88
+
89
+ - Use a managed database with backups, monitoring, and connection pooling.
90
+ - Keep local file databases such as `file:./mastra.db` out of multi-process production deployments.
91
+ - Route high-volume domains, especially `observability`, to a dedicated backend with [composite storage](#composite-storage).
92
+ - Configure [retention](https://mastra.ai/reference/storage/retention) policies on the storage adapter or composite store, then call `storage.prune()` from a scheduler or maintenance job.
93
+ - Choose providers based on the domains your application uses. For example, schedules require an adapter that implements the `schedules` domain.
94
+
95
+ ## Configuration scope
96
+
97
+ Storage can be configured at the Mastra instance level or at the agent level.
98
+
99
+ ### Instance-level storage
100
+
101
+ Instance-level storage is shared by agents, workflows, observability, evals, schedules, and other runtime features registered on the same Mastra instance.
102
+
103
+ **PostgreSQL**:
104
+
105
+ ```typescript
106
+ import { Mastra } from '@mastra/core'
107
+ import { PostgresStore } from '@mastra/pg'
108
+
109
+ export const mastra = new Mastra({
110
+ storage: new PostgresStore({
111
+ id: 'mastra-storage',
112
+ connectionString: process.env.DATABASE_URL,
113
+ }),
114
+ })
115
+ ```
116
+
117
+ **MongoDB**:
118
+
119
+ ```typescript
120
+ import { Mastra } from '@mastra/core'
121
+ import { MongoDBStore } from '@mastra/mongodb'
122
+
123
+ export const mastra = new Mastra({
124
+ storage: new MongoDBStore({
125
+ id: 'mastra-storage',
126
+ uri: process.env.MONGODB_URI,
127
+ dbName: process.env.MONGODB_DB_NAME,
128
+ }),
129
+ })
130
+ ```
131
+
132
+ Use instance-level storage when most runtime domains can share the same database.
133
+
134
+ ### Agent-level storage
135
+
136
+ Agent-level storage is configured on a `Memory` instance. It overrides instance-level storage for that agent's memory data only.
137
+
138
+ ```typescript
139
+ import { Agent } from '@mastra/core/agent'
140
+ import { Memory } from '@mastra/memory'
141
+ import { PostgresStore } from '@mastra/pg'
142
+
143
+ export const supportAgent = new Agent({
144
+ id: 'support-agent',
145
+ name: 'Support agent',
146
+ instructions: 'Answer customer support questions.',
147
+ model: 'openai/gpt-5.6-sol',
148
+ memory: new Memory({
149
+ storage: new PostgresStore({
150
+ id: 'support-agent-storage',
151
+ connectionString: process.env.SUPPORT_AGENT_DATABASE_URL,
152
+ }),
153
+ }),
154
+ })
155
+ ```
156
+
157
+ Use agent-level storage when an agent needs an isolated memory boundary or a different memory backend.
158
+
159
+ ## Composite storage
160
+
161
+ [`MastraCompositeStore`](https://mastra.ai/reference/storage/composite) routes domains to different backends. Use it when one database isn't the right fit for every domain.
162
+
163
+ The following example uses libSQL as the default store and routes workflow state to PostgreSQL:
164
+
165
+ ```typescript
166
+ import { Mastra } from '@mastra/core'
167
+ import { MastraCompositeStore } from '@mastra/core/storage'
168
+ import { LibSQLStore } from '@mastra/libsql'
169
+ import { WorkflowsPG } from '@mastra/pg'
170
+
171
+ export const mastra = new Mastra({
172
+ storage: new MastraCompositeStore({
173
+ id: 'composite-storage',
174
+ default: new LibSQLStore({
175
+ id: 'default-storage',
176
+ url: 'file:./mastra.db',
177
+ }),
178
+ domains: {
179
+ workflows: new WorkflowsPG({
180
+ connectionString: process.env.DATABASE_URL,
181
+ }),
182
+ },
183
+ }),
184
+ })
185
+ ```
186
+
187
+ You can also route `observability` to a dedicated analytics backend. See the [observability quickstart](https://mastra.ai/docs/observability/overview) for an observability-specific example.
188
+
189
+ ## Supported providers
190
+
191
+ Each provider page includes installation instructions, configuration parameters, and usage examples:
192
+
193
+ - [libSQL](https://mastra.ai/reference/storage/libsql)
194
+ - [PostgreSQL](https://mastra.ai/reference/storage/postgresql)
195
+ - [MongoDB](https://mastra.ai/reference/storage/mongodb)
196
+ - [Upstash](https://mastra.ai/reference/storage/upstash)
197
+ - [Redis](https://mastra.ai/reference/storage/redis)
198
+ - [Cloudflare D1](https://mastra.ai/reference/storage/cloudflare-d1)
199
+ - [Cloudflare KV & Durable Objects](https://mastra.ai/reference/storage/cloudflare)
200
+ - [Convex](https://mastra.ai/reference/storage/convex)
201
+ - [DynamoDB](https://mastra.ai/reference/storage/dynamodb)
202
+ - [LanceDB](https://mastra.ai/reference/storage/lance)
203
+ - [Microsoft SQL Server](https://mastra.ai/reference/storage/mssql)
204
+ - [Google Cloud Spanner](https://mastra.ai/reference/storage/spanner)
205
+
206
+ > **Tip:** libSQL is the fastest path for local development because it doesn't require running a separate database server.
207
+
208
+ ## Next steps
209
+
210
+ - [Composite storage](https://mastra.ai/reference/storage/composite)
211
+ - [Storage retention](https://mastra.ai/reference/storage/retention)
212
+ - [Storage schemas](https://mastra.ai/reference/storage/overview)
213
+ - [Memory](https://mastra.ai/docs/memory/overview)
214
+ - [Observability storage](https://mastra.ai/docs/observability/overview)