@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,348 @@
1
+ > Discover all available pages from the documentation index: https://mastra.ai/llms.txt
2
+
3
+ # Message history
4
+
5
+ Message history is the most basic and important form of memory. It gives the LLM a view of recent messages in the context window, enabling your agent to reference earlier exchanges and respond coherently.
6
+
7
+ You can also retrieve message history to display past conversations in your UI.
8
+
9
+ > **Info:** Each message belongs to a thread (the conversation) and a resource (the user or entity it's associated with). See [Threads and resources](#threads-and-resources) for more detail.
10
+
11
+ > **Warning:** When you use memory with a client application, send **only the new message** from the client instead of the full conversation history.
12
+ >
13
+ > Sending the full history is redundant because Mastra loads messages from storage, and it can cause message ordering bugs when client-side timestamps conflict with stored timestamps.
14
+ >
15
+ > For an AI SDK example, see [Using Mastra Memory](https://mastra.ai/guides/build-your-ui/ai-sdk-ui).
16
+
17
+ ## Threads and resources
18
+
19
+ Mastra organizes conversations using two identifiers:
20
+
21
+ - **Thread**: A conversation session containing a sequence of messages.
22
+ - **Resource**: The entity that owns the thread, such as a user, organization, project, or another domain entity in your application.
23
+
24
+ Studio automatically generates a thread and resource ID for you. When calling `stream()` or `generate()` yourself, provide these identifiers explicitly.
25
+
26
+ ## Getting started
27
+
28
+ Install the Mastra memory module along with a [storage adapter](https://mastra.ai/docs/storage/overview) for your database. The examples below use `@mastra/libsql`, which stores data locally in a `mastra.db` file.
29
+
30
+ **npm**:
31
+
32
+ ```bash
33
+ npm install @mastra/memory@latest @mastra/libsql@latest
34
+ ```
35
+
36
+ **pnpm**:
37
+
38
+ ```bash
39
+ pnpm add @mastra/memory@latest @mastra/libsql@latest
40
+ ```
41
+
42
+ **Yarn**:
43
+
44
+ ```bash
45
+ yarn add @mastra/memory@latest @mastra/libsql@latest
46
+ ```
47
+
48
+ **Bun**:
49
+
50
+ ```bash
51
+ bun add @mastra/memory@latest @mastra/libsql@latest
52
+ ```
53
+
54
+ Message history requires a storage adapter to persist conversations. Configure storage on your Mastra instance if you haven't already:
55
+
56
+ ```typescript
57
+ import { Mastra } from '@mastra/core'
58
+ import { LibSQLStore } from '@mastra/libsql'
59
+
60
+ export const mastra = new Mastra({
61
+ storage: new LibSQLStore({
62
+ id: 'mastra-storage',
63
+ url: 'file:./mastra.db',
64
+ }),
65
+ })
66
+ ```
67
+
68
+ Instantiate a [`Memory`](https://mastra.ai/reference/memory/memory-class) instance in your agent:
69
+
70
+ ```typescript
71
+ import { Memory } from '@mastra/memory'
72
+ import { Agent } from '@mastra/core/agent'
73
+
74
+ export const agent = new Agent({
75
+ id: 'test-agent',
76
+ memory: new Memory({
77
+ options: {
78
+ lastMessages: 10,
79
+ },
80
+ }),
81
+ })
82
+ ```
83
+
84
+ When you call the agent, messages are automatically saved to the database. You can specify a `threadId`, `resourceId`, and optional `metadata`:
85
+
86
+ **.generate()**:
87
+
88
+ ```typescript
89
+ await agent.generate('Hello', {
90
+ memory: {
91
+ thread: {
92
+ id: 'thread-123',
93
+ title: 'Support conversation',
94
+ metadata: { category: 'billing' },
95
+ },
96
+ resource: 'user-456',
97
+ },
98
+ })
99
+ ```
100
+
101
+ **.stream()**:
102
+
103
+ ```typescript
104
+ await agent.stream('Hello', {
105
+ memory: {
106
+ thread: {
107
+ id: 'thread-123',
108
+ title: 'Support conversation',
109
+ metadata: { category: 'billing' },
110
+ },
111
+ resource: 'user-456',
112
+ },
113
+ })
114
+ ```
115
+
116
+ > **Info:** Threads and messages are created automatically when you call `agent.generate()` or `agent.stream()`, but you can also create them manually with [`createThread()`](https://mastra.ai/reference/memory/createThread) and [`saveMessages()`](https://mastra.ai/reference/memory/memory-class).
117
+
118
+ You can use this history in two ways:
119
+
120
+ - **Automatic inclusion**: Mastra automatically fetches and includes recent messages in the context window. By default, it includes the last 10 messages, keeping agents grounded in the conversation. You can adjust this number with `lastMessages`, but in most cases you don't need to think about it.
121
+ - [**Manual querying**](#querying): For more control, use the `recall()` function to query threads and messages directly. This lets you choose exactly which memories are included in the context window, or fetch messages to render conversation history in your UI.
122
+
123
+ > **Tip:** When memory is enabled, [Studio](https://mastra.ai/docs/studio/overview) uses message history to display past conversations in the chat sidebar.
124
+
125
+ ## Thread title generation
126
+
127
+ Mastra can automatically generate descriptive thread titles from the conversation transcript when `generateTitle` is enabled. Use this option when you build a chat interface that renders conversation titles in a thread list or sidebar.
128
+
129
+ ```typescript
130
+ import { Agent } from '@mastra/core/agent'
131
+ import { Memory } from '@mastra/memory'
132
+
133
+ export const supportAgent = new Agent({
134
+ id: 'support-agent',
135
+ name: 'Support agent',
136
+ instructions: 'Answer customer support questions.',
137
+ model: 'openai/gpt-5.6-sol',
138
+ memory: new Memory({
139
+ options: {
140
+ generateTitle: true,
141
+ },
142
+ }),
143
+ })
144
+ ```
145
+
146
+ Title generation runs asynchronously after the agent responds and doesn't affect response time.
147
+
148
+ To optimize cost or behavior, provide a smaller [`model`](https://mastra.ai/models) and custom `instructions`:
149
+
150
+ ```typescript
151
+ import { Agent } from '@mastra/core/agent'
152
+ import { Memory } from '@mastra/memory'
153
+
154
+ export const supportAgent = new Agent({
155
+ id: 'support-agent',
156
+ name: 'Support agent',
157
+ instructions: 'Answer customer support questions.',
158
+ model: 'openai/gpt-5.6-sol',
159
+ memory: new Memory({
160
+ options: {
161
+ generateTitle: {
162
+ model: 'openai/gpt-5-mini',
163
+ instructions: 'Generate a one-word title.',
164
+ },
165
+ },
166
+ }),
167
+ })
168
+ ```
169
+
170
+ ## Accessing memory
171
+
172
+ To access memory functions for querying, cloning, or deleting threads and messages, call `getMemory()` on an agent:
173
+
174
+ ```typescript
175
+ const agent = mastra.getAgentById('test-agent')
176
+ const memory = await agent.getMemory()
177
+ ```
178
+
179
+ The `Memory` instance gives you access to functions for listing threads and recalling messages, plus cloning conversations, and more.
180
+
181
+ ## Querying
182
+
183
+ Use these methods to fetch threads and messages for displaying conversation history in your UI or for custom memory retrieval logic.
184
+
185
+ > **Warning:** The memory system doesn't enforce access control. Before running any query, verify in your application logic that the current user is authorized to access the `resourceId` being queried.
186
+
187
+ ### Threads
188
+
189
+ Use [`listThreads()`](https://mastra.ai/reference/memory/listThreads) to retrieve threads for a resource:
190
+
191
+ ```typescript
192
+ const result = await memory.listThreads({
193
+ filter: { resourceId: 'user-123' },
194
+ perPage: false,
195
+ })
196
+ ```
197
+
198
+ Paginate through threads:
199
+
200
+ ```typescript
201
+ const result = await memory.listThreads({
202
+ filter: { resourceId: 'user-123' },
203
+ page: 0,
204
+ perPage: 10,
205
+ })
206
+
207
+ console.log(result.threads) // thread objects
208
+ console.log(result.hasMore) // more pages available?
209
+ ```
210
+
211
+ You can also filter by metadata and control sort order:
212
+
213
+ ```typescript
214
+ const result = await memory.listThreads({
215
+ filter: {
216
+ resourceId: 'user-123',
217
+ metadata: { status: 'active' },
218
+ },
219
+ orderBy: { field: 'createdAt', direction: 'DESC' },
220
+ })
221
+ ```
222
+
223
+ To fetch a single thread by ID, use [`getThreadById()`](https://mastra.ai/reference/memory/getThreadById):
224
+
225
+ ```typescript
226
+ const thread = await memory.getThreadById({ threadId: 'thread-123' })
227
+ ```
228
+
229
+ ### Messages
230
+
231
+ Once you have a thread, use [`recall()`](https://mastra.ai/reference/memory/recall) to retrieve its messages. It supports pagination, date filtering, and [semantic search](https://mastra.ai/docs/memory/semantic-recall).
232
+
233
+ Basic recall returns all messages from a thread:
234
+
235
+ ```typescript
236
+ const { messages } = await memory.recall({
237
+ threadId: 'thread-123',
238
+ perPage: false,
239
+ })
240
+ ```
241
+
242
+ Paginate through messages:
243
+
244
+ ```typescript
245
+ const { messages } = await memory.recall({
246
+ threadId: 'thread-123',
247
+ page: 0,
248
+ perPage: 50,
249
+ })
250
+ ```
251
+
252
+ Filter by date range:
253
+
254
+ ```typescript
255
+ const { messages } = await memory.recall({
256
+ threadId: 'thread-123',
257
+ filter: {
258
+ dateRange: {
259
+ start: new Date('2025-01-01'),
260
+ end: new Date('2025-06-01'),
261
+ },
262
+ },
263
+ })
264
+ ```
265
+
266
+ Filter by shallow message metadata:
267
+
268
+ ```typescript
269
+ const { messages } = await memory.recall({
270
+ threadId: 'thread-123',
271
+ filter: {
272
+ metadata: {
273
+ category: 'billing',
274
+ escalated: true,
275
+ priority: 2,
276
+ archivedAt: null,
277
+ },
278
+ },
279
+ })
280
+ ```
281
+
282
+ Metadata filters match shallow scalar values only: `string`, finite `number`, `boolean`, and `null`.
283
+
284
+ All specified metadata keys use AND semantics. A `null` filter matches only an explicit `null` value. A missing metadata key doesn't match.
285
+
286
+ Metadata keys must start with a letter or underscore and contain only alphanumeric characters. They must be 128 characters or fewer and can't use reserved prototype keys such as `__proto__`, `constructor`, or `prototype`.
287
+
288
+ Performance depends on the storage backend. Some backends can push parts of the filter into the database, while others scan candidate messages after thread, resource, and date constraints are applied but before pagination.
289
+
290
+ Fetch a single message by ID:
291
+
292
+ ```typescript
293
+ const { messages } = await memory.recall({
294
+ threadId: 'thread-123',
295
+ include: [{ id: 'msg-123' }],
296
+ })
297
+ ```
298
+
299
+ Fetch multiple messages by ID with surrounding context:
300
+
301
+ ```typescript
302
+ const { messages } = await memory.recall({
303
+ threadId: 'thread-123',
304
+ include: [
305
+ { id: 'msg-123' },
306
+ {
307
+ id: 'msg-456',
308
+ withPreviousMessages: 3,
309
+ withNextMessages: 1,
310
+ },
311
+ ],
312
+ })
313
+ ```
314
+
315
+ Search by meaning (see [Semantic recall](https://mastra.ai/docs/memory/semantic-recall) for setup):
316
+
317
+ ```typescript
318
+ const { messages } = await memory.recall({
319
+ threadId: 'thread-123',
320
+ vectorSearchString: 'project deadline discussion',
321
+ threadConfig: {
322
+ semanticRecall: true,
323
+ },
324
+ })
325
+ ```
326
+
327
+ ### UI format
328
+
329
+ Message queries return `MastraDBMessage[]` format. To display messages in a frontend, you may need to convert them to a format your UI library expects. For example, [`toAISdkV5Messages`](https://mastra.ai/reference/ai-sdk/to-ai-sdk-v5-messages) converts messages to AI SDK UI format.
330
+
331
+ ## Thread cloning
332
+
333
+ Thread cloning creates a copy of an existing thread with its messages. This is useful for branching conversations or creating checkpoints before a potentially destructive operation, or alternatively testing variations of a conversation.
334
+
335
+ ```typescript
336
+ const { thread, clonedMessages } = await memory.cloneThread({
337
+ sourceThreadId: 'thread-123',
338
+ title: 'Branched conversation',
339
+ })
340
+ ```
341
+
342
+ You can filter which messages get cloned (by count or date range), specify custom thread IDs, and use utility methods to inspect clone relationships.
343
+
344
+ See [`cloneThread()`](https://mastra.ai/reference/memory/cloneThread) and [clone utilities](https://mastra.ai/reference/memory/clone-utilities) for the full API.
345
+
346
+ ## Deleting messages
347
+
348
+ To remove messages from a thread, use [`deleteMessages()`](https://mastra.ai/reference/memory/deleteMessages). You can delete by message ID or clear all messages from a thread.
@@ -0,0 +1,208 @@
1
+ > Discover all available pages from the documentation index: https://mastra.ai/llms.txt
2
+
3
+ # Multi-user threads
4
+
5
+ A single Mastra thread can be shared by multiple users, each with their own name and functional role. You carry speaker identity in the message body so the agent can tell users apart while reading from a single shared thread.
6
+
7
+ ## When to use multi-user threads
8
+
9
+ Use multi-user threads when several people collaborate on the same subject through one agent:
10
+
11
+ - Collaborative documents with editors, reviewers, and approvers
12
+ - Group chats where one assistant serves many participants
13
+ - Multi-stakeholder reviews where different roles have different authority
14
+
15
+ ## Share one `resourceId` across all participants
16
+
17
+ A thread belongs to exactly one `resourceId`, so all participants on a shared thread need to pass the same value. Instead of using a user id (the default for single-user apps), key `resourceId` on the conversation itself, for example `doc_${docId}` for a shared document, or `room_${roomId}` for a group chat. With everyone pointing at the same `resourceId`, they read and write the same history.
18
+
19
+ ## Tag each user message with the speaker's identity
20
+
21
+ The model needs to know who's talking on every turn. Since the message body is the one place that survives into history and back into context, wrap each user message in a small `<turn>` tag with the speaker's id, name, and role. The tag stays attached to the message, so when prior turns are recalled the model still sees who said what.
22
+
23
+ Build the tag with a small helper. The example below is one way to do it, copy it into your project and adapt it to your shape of user data:
24
+
25
+ ```typescript
26
+ export type Speaker = {
27
+ id: string
28
+ name: string
29
+ role: string
30
+ }
31
+
32
+ function escapeAttr(value: string) {
33
+ return value
34
+ .replace(/&/g, '&amp;')
35
+ .replace(/"/g, '&quot;')
36
+ .replace(/</g, '&lt;')
37
+ .replace(/>/g, '&gt;')
38
+ }
39
+
40
+ export function asUserTurn(speaker: Speaker, text: string) {
41
+ const id = escapeAttr(speaker.id)
42
+ const name = escapeAttr(speaker.name)
43
+ const role = escapeAttr(speaker.role)
44
+ return {
45
+ role: 'user' as const,
46
+ content: `<turn author_id="${id}" author_name="${name}" functional_role="${role}">
47
+ ${text}
48
+ </turn>`,
49
+ }
50
+ }
51
+ ```
52
+
53
+ Teach the agent how to read the `<turn>` tag in its instructions. The agent must have `memory` configured so it can be called with a `thread` and `resource`:
54
+
55
+ ```typescript
56
+ import { Agent } from '@mastra/core/agent'
57
+ import { Memory } from '@mastra/memory'
58
+ import { LibSQLStore } from '@mastra/libsql'
59
+
60
+ const memory = new Memory({
61
+ storage: new LibSQLStore({ id: 'collab-storage', url: 'file:./collab.db' }),
62
+ options: {
63
+ lastMessages: 20,
64
+ },
65
+ })
66
+
67
+ export const collabAgent = new Agent({
68
+ id: 'collab',
69
+ name: 'CollabAgent',
70
+ model: 'openai/gpt-5-mini',
71
+ memory,
72
+ instructions: `
73
+ You are a collaborative document assistant. Multiple users talk to you in the SAME thread.
74
+
75
+ Every user message is wrapped in a <turn> tag carrying the user's identity:
76
+
77
+ <turn author_id="u_alice" author_name="Alice" functional_role="editor">
78
+ ...message text...
79
+ </turn>
80
+
81
+ Rules:
82
+ 1. Address users by their author_name.
83
+ 2. Respect functional_role: editors propose changes, reviewers approve.
84
+ 3. When attributing past statements, read author_name from the surrounding <turn> tag.
85
+ 4. Do not echo the <turn> tags back at users.
86
+ `.trim(),
87
+ })
88
+ ```
89
+
90
+ Call the agent with the wrapped message. Every participant shares the same `thread` and `resource`:
91
+
92
+ ```typescript
93
+ import { asUserTurn } from './identity'
94
+
95
+ const docResourceId = 'doc_42'
96
+ const docThreadId = 'doc_42'
97
+
98
+ const alice = { id: 'u_alice', name: 'Alice', role: 'editor' }
99
+ const bob = { id: 'u_bob', name: 'Bob', role: 'reviewer' }
100
+
101
+ await collabAgent.generate([asUserTurn(alice, 'My favorite color is teal.')], {
102
+ memory: { thread: docThreadId, resource: docResourceId },
103
+ })
104
+
105
+ await collabAgent.generate([asUserTurn(bob, 'I want QA sign-off before publish.')], {
106
+ memory: { thread: docThreadId, resource: docResourceId },
107
+ })
108
+ ```
109
+
110
+ The `<turn>` tag persists in the message body, so when history is recalled on later turns the model still sees who said what.
111
+
112
+ ## Combining with memory layers
113
+
114
+ The user-tagging pattern composes with every memory layer. Pick the layer based on how long the conversation needs to remember per-user facts:
115
+
116
+ - **Short conversations** (a single session, or a thread small enough to fit in `lastMessages`), or when you need a verbatim record of who said what: use [message history alone](#message-history-alone). The user tags in history are enough. No extra memory layer needed.
117
+ - **Long-running threads** (conversations that outgrow `lastMessages`, where you need per-user facts to survive history eviction): use [observational memory](#with-observational-memory-recommended).
118
+ - **Need a structured participants list, or your storage adapter doesn't support OM** (OM requires LibSQL, PG, or MongoDB): use [working memory](#with-working-memory).
119
+
120
+ We recommend using either observational memory or working memory because they cover overlapping needs. Running both adds latency and token cost without much benefit.
121
+
122
+ ### Message history alone
123
+
124
+ For short conversations, or when you need a verbatim record of who said what, the user tags in history are enough. `lastMessages` brings prior turns back into context with their attribution intact:
125
+
126
+ ```typescript
127
+ import { Memory } from '@mastra/memory'
128
+ import { LibSQLStore } from '@mastra/libsql'
129
+
130
+ const memory = new Memory({
131
+ storage: new LibSQLStore({ id: 'collab-storage', url: 'file:./collab.db' }),
132
+ options: {
133
+ lastMessages: 20,
134
+ },
135
+ })
136
+ ```
137
+
138
+ The model reads identity from the `<turn>` tag on the current message and from prior tagged messages brought back through `lastMessages`.
139
+
140
+ ### With Observational Memory (recommended)
141
+
142
+ [Observational Memory](https://mastra.ai/docs/memory/observational-memory) (OM) extracts per-user facts into a background log without burning the agent's tool budget. The default Observer model reads `<turn>` tags natively and produces attribution like `Alice stated her favorite color is teal.` and `Bob asked for QA sign-off before publish.`
143
+
144
+ Prefer OM over working memory for multi-user threads when your storage supports it. OM extracts facts automatically, scales to any number of participants, and doesn't need template upkeep. Enable it with no overrides:
145
+
146
+ ```typescript
147
+ import { Memory } from '@mastra/memory'
148
+ import { LibSQLStore } from '@mastra/libsql'
149
+
150
+ const memory = new Memory({
151
+ storage: new LibSQLStore({ id: 'collab-storage', url: 'file:./collab.db' }),
152
+ options: {
153
+ lastMessages: 20,
154
+ observationalMemory: true,
155
+ },
156
+ })
157
+ ```
158
+
159
+ OM requires a storage adapter that supports it: `@mastra/libsql`, `@mastra/pg`, or `@mastra/mongodb`.
160
+
161
+ > **Note:** If you switch the Observer to a weaker model and see facts collapse to a generic `User`, use [`observation.instruction`](https://mastra.ai/reference/memory/observational-memory) to teach the Observer how to read the `<turn>` tag.
162
+
163
+ ### With working memory
164
+
165
+ Use working memory when OM isn't an option, for example, when your storage adapter doesn't support OM, or when you need a structured, deterministic participants list the agent can read and write on every turn.
166
+
167
+ The default [working memory](https://mastra.ai/docs/memory/working-memory) template assumes one user per thread ("First Name", "Last Name", etc.). For multi-user threads, provide a template with a participants list:
168
+
169
+ ```typescript
170
+ import { Memory } from '@mastra/memory'
171
+ import { LibSQLStore } from '@mastra/libsql'
172
+
173
+ const memory = new Memory({
174
+ storage: new LibSQLStore({ id: 'collab-storage', url: 'file:./collab.db' }),
175
+ options: {
176
+ lastMessages: 20,
177
+ workingMemory: {
178
+ enabled: true,
179
+ scope: 'thread',
180
+ template: `# Document Collaboration State
181
+
182
+ ## Participants
183
+ <!-- One entry per known collaborator. Use author_id as the stable key. -->
184
+ <!-- - **<author_name>** (<author_id>, <functional_role>): <their position> -->
185
+
186
+ ## Open Questions
187
+
188
+ ## Decisions
189
+ `,
190
+ },
191
+ },
192
+ })
193
+ ```
194
+
195
+ Set `scope: 'thread'` so the participants list belongs to the document, not to any individual user. Add one instruction telling the agent to append new participants to the list whenever a new `author_id` shows up in a `<turn>`.
196
+
197
+ For more on templates, see [Custom templates](https://mastra.ai/docs/memory/working-memory).
198
+
199
+ ## Security
200
+
201
+ Set the `speaker` from your authenticated request context, never from the request body. If a client can choose its own `author_id`, one user can impersonate another. Use [Request Context](https://mastra.ai/docs/server/request-context) to read the verified user from your auth layer and build the `<turn>` tag on the server before calling the agent.
202
+
203
+ ## Related
204
+
205
+ - [Working memory](https://mastra.ai/docs/memory/working-memory)
206
+ - [Observational memory](https://mastra.ai/docs/memory/observational-memory)
207
+ - [Share memory between agents](https://mastra.ai/docs/memory/overview)
208
+ - [`Memory` reference](https://mastra.ai/reference/memory/memory-class)