@mastra/memory 1.1.0 → 1.2.0-alpha.1

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 (95) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/dist/_types/@internal_ai-sdk-v4/dist/index.d.ts +30 -17
  3. package/dist/{chunk-6TXUWFIU.js → chunk-5YW6JV6Y.js} +1958 -321
  4. package/dist/chunk-5YW6JV6Y.js.map +1 -0
  5. package/dist/{chunk-FQJWVCDF.cjs → chunk-7SCXX4S7.cjs} +1957 -320
  6. package/dist/chunk-7SCXX4S7.cjs.map +1 -0
  7. package/dist/chunk-EQ4M72KU.js +439 -0
  8. package/dist/chunk-EQ4M72KU.js.map +1 -0
  9. package/dist/{chunk-O3CS4UGX.cjs → chunk-IDRQZVB4.cjs} +4 -4
  10. package/dist/{chunk-O3CS4UGX.cjs.map → chunk-IDRQZVB4.cjs.map} +1 -1
  11. package/dist/{chunk-YF4R74L2.js → chunk-RC6RZVYE.js} +4 -4
  12. package/dist/{chunk-YF4R74L2.js.map → chunk-RC6RZVYE.js.map} +1 -1
  13. package/dist/chunk-ZD3BKU5O.cjs +441 -0
  14. package/dist/chunk-ZD3BKU5O.cjs.map +1 -0
  15. package/dist/docs/SKILL.md +51 -50
  16. package/dist/docs/{SOURCE_MAP.json → assets/SOURCE_MAP.json} +22 -22
  17. package/dist/docs/{agents/03-agent-approval.md → references/docs-agents-agent-approval.md} +19 -19
  18. package/dist/docs/references/docs-agents-agent-memory.md +212 -0
  19. package/dist/docs/{agents/04-network-approval.md → references/docs-agents-network-approval.md} +13 -12
  20. package/dist/docs/{agents/02-networks.md → references/docs-agents-networks.md} +10 -12
  21. package/dist/docs/{memory/06-memory-processors.md → references/docs-memory-memory-processors.md} +6 -8
  22. package/dist/docs/{memory/03-message-history.md → references/docs-memory-message-history.md} +31 -20
  23. package/dist/docs/references/docs-memory-observational-memory.md +169 -0
  24. package/dist/docs/{memory/01-overview.md → references/docs-memory-overview.md} +8 -8
  25. package/dist/docs/{memory/05-semantic-recall.md → references/docs-memory-semantic-recall.md} +33 -17
  26. package/dist/docs/{memory/02-storage.md → references/docs-memory-storage.md} +29 -39
  27. package/dist/docs/{memory/04-working-memory.md → references/docs-memory-working-memory.md} +16 -27
  28. package/dist/docs/references/reference-core-getMemory.md +50 -0
  29. package/dist/docs/references/reference-core-listMemory.md +56 -0
  30. package/dist/docs/references/reference-memory-clone-utilities.md +199 -0
  31. package/dist/docs/references/reference-memory-cloneThread.md +130 -0
  32. package/dist/docs/references/reference-memory-createThread.md +68 -0
  33. package/dist/docs/references/reference-memory-getThreadById.md +24 -0
  34. package/dist/docs/references/reference-memory-listThreads.md +145 -0
  35. package/dist/docs/references/reference-memory-memory-class.md +147 -0
  36. package/dist/docs/references/reference-memory-observational-memory.md +219 -0
  37. package/dist/docs/{processors/01-reference.md → references/reference-processors-token-limiter-processor.md} +25 -12
  38. package/dist/docs/references/reference-storage-dynamodb.md +282 -0
  39. package/dist/docs/references/reference-storage-libsql.md +135 -0
  40. package/dist/docs/references/reference-storage-mongodb.md +262 -0
  41. package/dist/docs/references/reference-storage-postgresql.md +529 -0
  42. package/dist/docs/references/reference-storage-upstash.md +160 -0
  43. package/dist/docs/references/reference-vectors-libsql.md +305 -0
  44. package/dist/docs/references/reference-vectors-mongodb.md +295 -0
  45. package/dist/docs/references/reference-vectors-pg.md +408 -0
  46. package/dist/docs/references/reference-vectors-upstash.md +294 -0
  47. package/dist/index.cjs +919 -507
  48. package/dist/index.cjs.map +1 -1
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +914 -502
  51. package/dist/index.js.map +1 -1
  52. package/dist/{observational-memory-3Q42SITP.cjs → observational-memory-G3HACXHE.cjs} +14 -14
  53. package/dist/{observational-memory-3Q42SITP.cjs.map → observational-memory-G3HACXHE.cjs.map} +1 -1
  54. package/dist/{observational-memory-VXLHOSDZ.js → observational-memory-LI6QFTRE.js} +3 -3
  55. package/dist/{observational-memory-VXLHOSDZ.js.map → observational-memory-LI6QFTRE.js.map} +1 -1
  56. package/dist/processors/index.cjs +12 -12
  57. package/dist/processors/index.js +1 -1
  58. package/dist/processors/observational-memory/index.d.ts +1 -1
  59. package/dist/processors/observational-memory/index.d.ts.map +1 -1
  60. package/dist/processors/observational-memory/observational-memory.d.ts +283 -1
  61. package/dist/processors/observational-memory/observational-memory.d.ts.map +1 -1
  62. package/dist/processors/observational-memory/observer-agent.d.ts +3 -1
  63. package/dist/processors/observational-memory/observer-agent.d.ts.map +1 -1
  64. package/dist/processors/observational-memory/reflector-agent.d.ts +10 -3
  65. package/dist/processors/observational-memory/reflector-agent.d.ts.map +1 -1
  66. package/dist/processors/observational-memory/types.d.ts +243 -19
  67. package/dist/processors/observational-memory/types.d.ts.map +1 -1
  68. package/dist/{token-6GSAFR2W-WGTMOPEU.js → token-APYSY3BW-2DN6RAUY.js} +11 -11
  69. package/dist/token-APYSY3BW-2DN6RAUY.js.map +1 -0
  70. package/dist/{token-6GSAFR2W-2B4WM6AQ.cjs → token-APYSY3BW-ZQ7TMBY7.cjs} +14 -14
  71. package/dist/token-APYSY3BW-ZQ7TMBY7.cjs.map +1 -0
  72. package/dist/token-util-RMHT2CPJ-6TGPE335.cjs +10 -0
  73. package/dist/token-util-RMHT2CPJ-6TGPE335.cjs.map +1 -0
  74. package/dist/token-util-RMHT2CPJ-RJEA3FAN.js +8 -0
  75. package/dist/token-util-RMHT2CPJ-RJEA3FAN.js.map +1 -0
  76. package/dist/tools/working-memory.d.ts.map +1 -1
  77. package/package.json +5 -6
  78. package/dist/chunk-6TXUWFIU.js.map +0 -1
  79. package/dist/chunk-FQJWVCDF.cjs.map +0 -1
  80. package/dist/chunk-WM6IIUQW.js +0 -250
  81. package/dist/chunk-WM6IIUQW.js.map +0 -1
  82. package/dist/chunk-ZSBBXHNM.cjs +0 -252
  83. package/dist/chunk-ZSBBXHNM.cjs.map +0 -1
  84. package/dist/docs/README.md +0 -36
  85. package/dist/docs/agents/01-agent-memory.md +0 -166
  86. package/dist/docs/core/01-reference.md +0 -114
  87. package/dist/docs/memory/07-reference.md +0 -687
  88. package/dist/docs/storage/01-reference.md +0 -1218
  89. package/dist/docs/vectors/01-reference.md +0 -942
  90. package/dist/token-6GSAFR2W-2B4WM6AQ.cjs.map +0 -1
  91. package/dist/token-6GSAFR2W-WGTMOPEU.js.map +0 -1
  92. package/dist/token-util-NEHG7TUY-TV2H7N56.js +0 -8
  93. package/dist/token-util-NEHG7TUY-TV2H7N56.js.map +0 -1
  94. package/dist/token-util-NEHG7TUY-WJZIPNNX.cjs +0 -10
  95. package/dist/token-util-NEHG7TUY-WJZIPNNX.cjs.map +0 -1
@@ -1,8 +1,6 @@
1
- > Learn how to configure working memory in Mastra to store persistent user data, preferences.
2
-
3
1
  # Working Memory
4
2
 
5
- While [message history](https://mastra.ai/docs/memory/message-history) and [semantic recall](./semantic-recall) help agents remember conversations, working memory allows them to maintain persistent information about users across interactions.
3
+ 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
4
 
7
5
  Think of it as the agent's active thoughts or scratchpad – the key information they keep available about the user or task. It's similar to how a person would naturally remember someone's name, preferences, or important details during a conversation.
8
6
 
@@ -19,7 +17,7 @@ Working memory can persist at two different scopes:
19
17
 
20
18
  Here's a minimal example of setting up an agent with working memory:
21
19
 
22
- ```typescript {11-15}
20
+ ```typescript
23
21
  import { Agent } from "@mastra/core/agent";
24
22
  import { Memory } from "@mastra/memory";
25
23
 
@@ -43,7 +41,7 @@ const agent = new Agent({
43
41
 
44
42
  Working memory is a block of Markdown text that the agent is able to update over time to store continuously relevant information:
45
43
 
46
- <YouTube id="UMy_JHLf1n8" />
44
+ [YouTube video player](https://www.youtube-nocookie.com/embed/UMy_JHLf1n8)
47
45
 
48
46
  ## Memory Persistence Scopes
49
47
 
@@ -136,7 +134,7 @@ Templates guide the agent on what information to track and update in working mem
136
134
 
137
135
  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:
138
136
 
139
- ```typescript {5-28}
137
+ ```typescript
140
138
  const memory = new Memory({
141
139
  options: {
142
140
  workingMemory: {
@@ -172,19 +170,13 @@ const memory = new Memory({
172
170
 
173
171
  ## Designing Effective Templates
174
172
 
175
- A well-structured template keeps the information easy for the agent to parse and update. Treat the
176
- template as a short form that you want the assistant to keep up to date.
173
+ A well-structured template keeps the information easy for the agent to parse and update. Treat the template as a short form that you want the assistant to keep up to date.
177
174
 
178
- - **Short, focused labels.** Avoid paragraphs or very long headings. Keep labels brief (for example
179
- `## Personal Info` or `- Name:`) so updates are easy to read and less likely to be truncated.
180
- - **Use consistent casing.** Inconsistent capitalization (`Timezone:` vs `timezone:`) can cause messy
181
- updates. Stick to Title Case or lower case for headings and bullet labels.
182
- - **Keep placeholder text simple.** Use hints such as `[e.g., Formal]` or `[Date]` to help the LLM
183
- fill in the correct spots.
184
- - **Abbreviate very long values.** If you only need a short form, include guidance like
185
- `- Name: [First name or nickname]` or `- Address (short):` rather than the full legal text.
186
- - **Mention update rules in `instructions`.** You can instruct how and when to fill or clear parts of
187
- the template directly in the agent's `instructions` field.
175
+ - **Short, focused labels.** Avoid paragraphs or very long headings. Keep labels brief (for example `## Personal Info` or `- Name:`) so updates are easy to read and less likely to be truncated.
176
+ - **Use consistent casing.** Inconsistent capitalization (`Timezone:` vs `timezone:`) can cause messy updates. Stick to Title Case or lower case for headings and bullet labels.
177
+ - **Keep placeholder text simple.** Use hints such as `[e.g., Formal]` or `[Date]` to help the LLM fill in the correct spots.
178
+ - **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.
179
+ - **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.
188
180
 
189
181
  ### Alternative Template Styles
190
182
 
@@ -281,8 +273,7 @@ Schema-based working memory uses **merge semantics**, meaning the agent only nee
281
273
 
282
274
  ## Example: Multi-step Retention
283
275
 
284
- Below is a simplified view of how the `User Profile` template updates across a short user
285
- conversation:
276
+ Below is a simplified view of how the `User Profile` template updates across a short user conversation:
286
277
 
287
278
  ```nohighlight
288
279
  # User Profile
@@ -308,11 +299,9 @@ conversation:
308
299
  - Timezone: CET
309
300
  ```
310
301
 
311
- The agent can now refer to `Sam` or `Berlin` in later responses without requesting the information
312
- again because it has been stored in working memory.
302
+ 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.
313
303
 
314
- If your agent is not properly updating working memory when you expect it to, you can add system
315
- instructions on _how_ and _when_ to use this template in your agent's `instructions` setting.
304
+ If your agent is not 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.
316
305
 
317
306
  ## Setting Initial Working Memory
318
307
 
@@ -322,7 +311,7 @@ While agents typically update working memory through the `updateWorkingMemory` t
322
311
 
323
312
  When creating a thread, you can provide initial working memory through the metadata's `workingMemory` key:
324
313
 
325
- ```typescript title="src/app/medical-consultation.ts"
314
+ ```typescript
326
315
  // Create a thread with initial working memory
327
316
  const thread = await memory.createThread({
328
317
  threadId: "thread-123",
@@ -353,7 +342,7 @@ await agent.generate("What's my blood type?", {
353
342
 
354
343
  You can also update an existing thread's working memory:
355
344
 
356
- ```typescript title="src/app/medical-consultation.ts"
345
+ ```typescript
357
346
  // Update thread metadata to add/modify working memory
358
347
  await memory.updateThread({
359
348
  id: "thread-123",
@@ -375,7 +364,7 @@ await memory.updateThread({
375
364
 
376
365
  Alternatively, use the `updateWorkingMemory` method directly:
377
366
 
378
- ```typescript title="src/app/medical-consultation.ts"
367
+ ```typescript
379
368
  await memory.updateWorkingMemory({
380
369
  threadId: "thread-123",
381
370
  resourceId: "user-456", // Required for resource-scoped memory
@@ -0,0 +1,50 @@
1
+ # Mastra.getMemory()
2
+
3
+ The `.getMemory()` method retrieves a memory instance from the Mastra registry by its key. Memory instances are registered in the Mastra constructor and can be referenced by stored agents.
4
+
5
+ ## Usage example
6
+
7
+ ```typescript
8
+ const memory = mastra.getMemory("conversationMemory");
9
+
10
+ // Use the memory instance
11
+ const thread = await memory.createThread({
12
+ resourceId: "user-123",
13
+ title: "New Conversation",
14
+ });
15
+ ```
16
+
17
+ ## Parameters
18
+
19
+ **key:** (`TMemoryKey extends keyof TMemory`): The registry key of the memory instance to retrieve. Must match a key used when registering memory in the Mastra constructor.
20
+
21
+ ## Returns
22
+
23
+ **memory:** (`TMemory[TMemoryKey]`): The memory instance with the specified key. Throws an error if the memory is not found.
24
+
25
+ ## Example: Registering and Retrieving Memory
26
+
27
+ ```typescript
28
+ import { Mastra } from "@mastra/core";
29
+ import { Memory } from "@mastra/memory";
30
+ import { LibSQLStore } from "@mastra/libsql";
31
+
32
+ const conversationMemory = new Memory({
33
+ storage: new LibSQLStore({ id: 'conversation-store', url: ":memory:" }),
34
+ });
35
+
36
+ const mastra = new Mastra({
37
+ memory: {
38
+ conversationMemory,
39
+ },
40
+ });
41
+
42
+ // Later, retrieve the memory instance
43
+ const memory = mastra.getMemory("conversationMemory");
44
+ ```
45
+
46
+ ## Related
47
+
48
+ - [Mastra.listMemory()](https://mastra.ai/reference/core/listMemory)
49
+ - [Memory overview](https://mastra.ai/docs/memory/overview)
50
+ - [Agent Memory](https://mastra.ai/docs/agents/agent-memory)
@@ -0,0 +1,56 @@
1
+ # Mastra.listMemory()
2
+
3
+ The `.listMemory()` method returns all memory instances registered with the Mastra instance.
4
+
5
+ ## Usage example
6
+
7
+ ```typescript
8
+ const memoryInstances = mastra.listMemory();
9
+
10
+ for (const [key, memory] of Object.entries(memoryInstances)) {
11
+ console.log(`Memory "${key}": ${memory.id}`);
12
+ }
13
+ ```
14
+
15
+ ## Parameters
16
+
17
+ This method takes no parameters.
18
+
19
+ ## Returns
20
+
21
+ **memory:** (`Record<string, MastraMemory>`): An object containing all registered memory instances, keyed by their registry keys.
22
+
23
+ ## Example: Checking Registered Memory
24
+
25
+ ```typescript
26
+ import { Mastra } from "@mastra/core";
27
+ import { Memory } from "@mastra/memory";
28
+ import { LibSQLStore } from "@mastra/libsql";
29
+
30
+ const conversationMemory = new Memory({
31
+ id: "conversation-memory",
32
+ storage: new LibSQLStore({ id: 'conversation-store', url: ":memory:" }),
33
+ });
34
+
35
+ const analyticsMemory = new Memory({
36
+ id: "analytics-memory",
37
+ storage: new LibSQLStore({ id: 'analytics-store', url: ":memory:" }),
38
+ });
39
+
40
+ const mastra = new Mastra({
41
+ memory: {
42
+ conversationMemory,
43
+ analyticsMemory,
44
+ },
45
+ });
46
+
47
+ // List all registered memory instances
48
+ const allMemory = mastra.listMemory();
49
+ console.log(Object.keys(allMemory)); // ["conversationMemory", "analyticsMemory"]
50
+ ```
51
+
52
+ ## Related
53
+
54
+ - [Mastra.getMemory()](https://mastra.ai/reference/core/getMemory)
55
+ - [Memory overview](https://mastra.ai/docs/memory/overview)
56
+ - [Agent Memory](https://mastra.ai/docs/agents/agent-memory)
@@ -0,0 +1,199 @@
1
+ # Cloned Thread Utilities
2
+
3
+ The Memory class provides utility methods for working with cloned threads. These methods help you check clone status, retrieve clone metadata, navigate clone relationships, and track clone history.
4
+
5
+ ## isClone()
6
+
7
+ Checks whether a thread is a clone of another thread.
8
+
9
+ ### Usage
10
+
11
+ ```typescript
12
+ const isClonedThread = memory.isClone(thread);
13
+ ```
14
+
15
+ ### Parameters
16
+
17
+ **thread:** (`StorageThreadType`): The thread object to check.
18
+
19
+ ### Example
20
+
21
+ ```typescript
22
+ const thread = await memory.getThreadById({ threadId: "some-thread-id" });
23
+
24
+ if (memory.isClone(thread)) {
25
+ console.log("This thread was cloned from another thread");
26
+ } else {
27
+ console.log("This is an original thread");
28
+ }
29
+ ```
30
+
31
+ ## getCloneMetadata()
32
+
33
+ Retrieves the clone metadata from a thread if it exists.
34
+
35
+ ### Usage
36
+
37
+ ```typescript
38
+ const metadata = memory.getCloneMetadata(thread);
39
+ ```
40
+
41
+ ### Parameters
42
+
43
+ **thread:** (`StorageThreadType`): The thread object to extract clone metadata from.
44
+
45
+ ### Example
46
+
47
+ ```typescript
48
+ const thread = await memory.getThreadById({ threadId: "cloned-thread-id" });
49
+ const cloneInfo = memory.getCloneMetadata(thread);
50
+
51
+ if (cloneInfo) {
52
+ console.log(`Cloned from: ${cloneInfo.sourceThreadId}`);
53
+ console.log(`Cloned at: ${cloneInfo.clonedAt}`);
54
+ }
55
+ ```
56
+
57
+ ## getSourceThread()
58
+
59
+ Retrieves the original source thread that a cloned thread was created from.
60
+
61
+ ### Usage
62
+
63
+ ```typescript
64
+ const sourceThread = await memory.getSourceThread(threadId);
65
+ ```
66
+
67
+ ### Parameters
68
+
69
+ **threadId:** (`string`): The ID of the cloned thread.
70
+
71
+ ### Example
72
+
73
+ ```typescript
74
+ const sourceThread = await memory.getSourceThread("cloned-thread-id");
75
+
76
+ if (sourceThread) {
77
+ console.log(`Original thread title: ${sourceThread.title}`);
78
+ console.log(`Original thread created: ${sourceThread.createdAt}`);
79
+ }
80
+ ```
81
+
82
+ ## listClones()
83
+
84
+ Lists all threads that were cloned from a specific source thread.
85
+
86
+ ### Usage
87
+
88
+ ```typescript
89
+ const clones = await memory.listClones(sourceThreadId);
90
+ ```
91
+
92
+ ### Parameters
93
+
94
+ **sourceThreadId:** (`string`): The ID of the source thread to find clones for.
95
+
96
+ ### Example
97
+
98
+ ```typescript
99
+ const clones = await memory.listClones("original-thread-id");
100
+
101
+ console.log(`Found ${clones.length} clones`);
102
+ for (const clone of clones) {
103
+ console.log(`- ${clone.id}: ${clone.title}`);
104
+ }
105
+ ```
106
+
107
+ ## getCloneHistory()
108
+
109
+ Retrieves the full clone history chain for a thread, tracing back to the original.
110
+
111
+ ### Usage
112
+
113
+ ```typescript
114
+ const history = await memory.getCloneHistory(threadId);
115
+ ```
116
+
117
+ ### Parameters
118
+
119
+ **threadId:** (`string`): The ID of the thread to get clone history for.
120
+
121
+ ### Example
122
+
123
+ ```typescript
124
+ // If thread-c was cloned from thread-b, which was cloned from thread-a
125
+ const history = await memory.getCloneHistory("thread-c");
126
+
127
+ // history = [thread-a, thread-b, thread-c]
128
+ console.log(`Clone depth: ${history.length - 1}`);
129
+ console.log(`Original thread: ${history[0].id}`);
130
+ console.log(`Current thread: ${history[history.length - 1].id}`);
131
+
132
+ // Display the clone chain
133
+ for (let i = 0; i < history.length; i++) {
134
+ const prefix = i === 0 ? "Original" : `Clone ${i}`;
135
+ console.log(`${prefix}: ${history[i].title}`);
136
+ }
137
+ ```
138
+
139
+ ## Complete Example
140
+
141
+ ```typescript
142
+ import { mastra } from "./mastra";
143
+
144
+ async function manageClones() {
145
+ const agent = mastra.getAgent("agent");
146
+ const memory = await agent.getMemory();
147
+
148
+ // Create an original conversation
149
+ const originalThread = await memory.createThread({
150
+ resourceId: "user-123",
151
+ title: "Original Conversation",
152
+ });
153
+
154
+ // Have a conversation...
155
+ await agent.generate("Hello! Let's discuss project options.", {
156
+ threadId: originalThread.id,
157
+ resourceId: "user-123",
158
+ });
159
+
160
+ // Create multiple branches (clones) to explore different paths
161
+ const { thread: optionA } = await memory.cloneThread({
162
+ sourceThreadId: originalThread.id,
163
+ title: "Option A - Conservative Approach",
164
+ });
165
+
166
+ const { thread: optionB } = await memory.cloneThread({
167
+ sourceThreadId: originalThread.id,
168
+ title: "Option B - Aggressive Approach",
169
+ });
170
+
171
+ // Check clone status
172
+ console.log(memory.isClone(originalThread)); // false
173
+ console.log(memory.isClone(optionA)); // true
174
+ console.log(memory.isClone(optionB)); // true
175
+
176
+ // Get clone metadata
177
+ const metadataA = memory.getCloneMetadata(optionA);
178
+ console.log(metadataA?.sourceThreadId); // originalThread.id
179
+
180
+ // List all clones of the original
181
+ const allClones = await memory.listClones(originalThread.id);
182
+ console.log(`Total alternatives: ${allClones.length}`); // 2
183
+
184
+ // Get source thread from a clone
185
+ const source = await memory.getSourceThread(optionA.id);
186
+ console.log(source?.id === originalThread.id); // true
187
+
188
+ // Create a deeper clone chain
189
+ const { thread: optionA2 } = await memory.cloneThread({
190
+ sourceThreadId: optionA.id,
191
+ title: "Option A - Variant 2",
192
+ });
193
+
194
+ // Get the full history
195
+ const history = await memory.getCloneHistory(optionA2.id);
196
+ // history = [originalThread, optionA, optionA2]
197
+ console.log(`Clone depth: ${history.length - 1}`); // 2
198
+ }
199
+ ```
@@ -0,0 +1,130 @@
1
+ # Memory.cloneThread()
2
+
3
+ The `.cloneThread()` method creates a copy of an existing conversation thread, including all its messages. This enables creating divergent conversation paths from a specific point in a conversation. When semantic recall is enabled, the method also creates vector embeddings for the cloned messages.
4
+
5
+ ## Usage Example
6
+
7
+ ```typescript
8
+ const { thread, clonedMessages } = await memory.cloneThread({
9
+ sourceThreadId: "original-thread-123",
10
+ });
11
+ ```
12
+
13
+ ## Parameters
14
+
15
+ **sourceThreadId:** (`string`): The ID of the thread to clone
16
+
17
+ **newThreadId?:** (`string`): Optional custom ID for the cloned thread. If not provided, one will be generated.
18
+
19
+ **resourceId?:** (`string`): Optional resource ID for the cloned thread. Defaults to the source thread's resourceId.
20
+
21
+ **title?:** (`string`): Optional title for the cloned thread. Defaults to '\[source title] (Copy)'.
22
+
23
+ **metadata?:** (`Record<string, unknown>`): Optional metadata to merge with the source thread's metadata. Clone metadata is automatically added.
24
+
25
+ **options?:** (`CloneOptions`): Optional filtering options for the clone operation.
26
+
27
+ ### Options Parameters
28
+
29
+ **messageLimit?:** (`number`): Maximum number of messages to clone. When set, clones the most recent N messages.
30
+
31
+ **messageFilter?:** (`MessageFilter`): Filter criteria for selecting which messages to clone.
32
+
33
+ ### MessageFilter Parameters
34
+
35
+ **startDate?:** (`Date`): Only clone messages created on or after this date.
36
+
37
+ **endDate?:** (`Date`): Only clone messages created on or before this date.
38
+
39
+ **messageIds?:** (`string[]`): Only clone messages with these specific IDs.
40
+
41
+ ## Returns
42
+
43
+ **thread:** (`StorageThreadType`): The newly created cloned thread with clone metadata.
44
+
45
+ **clonedMessages:** (`MastraDBMessage[]`): Array of the cloned messages with new IDs assigned to the new thread.
46
+
47
+ ### Clone Metadata
48
+
49
+ The cloned thread's metadata includes a `clone` property with:
50
+
51
+ **sourceThreadId:** (`string`): The ID of the original thread that was cloned.
52
+
53
+ **clonedAt:** (`Date`): Timestamp when the clone was created.
54
+
55
+ **lastMessageId?:** (`string`): The ID of the last message in the source thread at the time of cloning.
56
+
57
+ ## Extended Usage Example
58
+
59
+ ```typescript
60
+ import { mastra } from "./mastra";
61
+
62
+ const agent = mastra.getAgent("agent");
63
+ const memory = await agent.getMemory();
64
+
65
+ // Clone a thread with all messages
66
+ const { thread: fullClone } = await memory.cloneThread({
67
+ sourceThreadId: "original-thread-123",
68
+ title: "Alternative Conversation Path",
69
+ });
70
+
71
+ // Clone with a custom ID
72
+ const { thread: customIdClone } = await memory.cloneThread({
73
+ sourceThreadId: "original-thread-123",
74
+ newThreadId: "my-custom-clone-id",
75
+ });
76
+
77
+ // Clone only the last 5 messages
78
+ const { thread: partialClone, clonedMessages } = await memory.cloneThread({
79
+ sourceThreadId: "original-thread-123",
80
+ options: {
81
+ messageLimit: 5,
82
+ },
83
+ });
84
+
85
+ // Clone messages from a specific date range
86
+ const { thread: dateFilteredClone } = await memory.cloneThread({
87
+ sourceThreadId: "original-thread-123",
88
+ options: {
89
+ messageFilter: {
90
+ startDate: new Date("2024-01-01"),
91
+ endDate: new Date("2024-01-31"),
92
+ },
93
+ },
94
+ });
95
+
96
+ // Continue conversation on the cloned thread
97
+ const response = await agent.generate("Let's try a different approach", {
98
+ threadId: fullClone.id,
99
+ resourceId: fullClone.resourceId,
100
+ });
101
+ ```
102
+
103
+ ## Vector Embeddings
104
+
105
+ When the Memory instance has semantic recall enabled (with a vector store and embedder configured), `cloneThread()` automatically creates vector embeddings for all cloned messages. This ensures that semantic search works correctly on the cloned thread.
106
+
107
+ ```typescript
108
+ import { Memory } from "@mastra/memory";
109
+ import { LibSQLStore, LibSQLVector } from "@mastra/libsql";
110
+
111
+ const memory = new Memory({
112
+ storage: new LibSQLStore({ id: 'memory-store', url: "file:./memory.db" }),
113
+ vector: new LibSQLVector({ id: 'vector-store', url: "file:./vector.db" }),
114
+ embedder: embeddingModel,
115
+ options: {
116
+ semanticRecall: true,
117
+ },
118
+ });
119
+
120
+ // Clone will also create embeddings for cloned messages
121
+ const { thread } = await memory.cloneThread({
122
+ sourceThreadId: "original-thread",
123
+ });
124
+
125
+ // Semantic search works on the cloned thread
126
+ const results = await memory.recall({
127
+ threadId: thread.id,
128
+ vectorSearchString: "search query",
129
+ });
130
+ ```
@@ -0,0 +1,68 @@
1
+ # Memory.createThread()
2
+
3
+ The `.createThread()` method creates a new conversation thread in the memory system. Each thread represents a distinct conversation or context and can contain multiple messages.
4
+
5
+ ## Usage Example
6
+
7
+ ```typescript
8
+ await memory?.createThread({ resourceId: "user-123" });
9
+ ```
10
+
11
+ ## Parameters
12
+
13
+ **resourceId:** (`string`): Identifier for the resource this thread belongs to (e.g., user ID, project ID)
14
+
15
+ **threadId?:** (`string`): Optional custom ID for the thread. If not provided, one will be generated.
16
+
17
+ **title?:** (`string`): Optional title for the thread
18
+
19
+ **metadata?:** (`Record<string, unknown>`): Optional metadata to associate with the thread
20
+
21
+ ## Returns
22
+
23
+ **id:** (`string`): Unique identifier of the created thread
24
+
25
+ **resourceId:** (`string`): Resource ID associated with the thread
26
+
27
+ **title:** (`string`): Title of the thread (if provided)
28
+
29
+ **createdAt:** (`Date`): Timestamp when the thread was created
30
+
31
+ **updatedAt:** (`Date`): Timestamp when the thread was last updated
32
+
33
+ **metadata:** (`Record<string, unknown>`): Additional metadata associated with the thread
34
+
35
+ ## Extended usage example
36
+
37
+ ```typescript
38
+ import { mastra } from "./mastra";
39
+
40
+ const agent = mastra.getAgent("agent");
41
+ const memory = await agent.getMemory();
42
+
43
+ const thread = await memory?.createThread({
44
+ resourceId: "user-123",
45
+ title: "Memory Test Thread",
46
+ metadata: {
47
+ source: "test-script",
48
+ purpose: "memory-testing",
49
+ },
50
+ });
51
+
52
+ const response = await agent.generate("message for agent", {
53
+ memory: {
54
+ thread: thread!.id,
55
+ resource: thread!.resourceId,
56
+ },
57
+ });
58
+
59
+ console.log(response.text);
60
+ ```
61
+
62
+ ### Related
63
+
64
+ - [Memory Class Reference](https://mastra.ai/reference/memory/memory-class)
65
+ - [Getting Started with Memory](https://mastra.ai/docs/memory/overview) (Covers threads concept)
66
+ - [getThreadById](https://mastra.ai/reference/memory/getThreadById)
67
+ - [listThreads](https://mastra.ai/reference/memory/listThreads)
68
+ - [recall](https://mastra.ai/reference/memory/recall)
@@ -0,0 +1,24 @@
1
+ # Memory.getThreadById()
2
+
3
+ The `.getThreadById()` method retrieves a specific thread by its ID.
4
+
5
+ ## Usage Example
6
+
7
+ ```typescript
8
+ await memory?.getThreadById({ threadId: "thread-123" });
9
+ ```
10
+
11
+ ## Parameters
12
+
13
+ **threadId:** (`string`): The ID of the thread to be retrieved.
14
+
15
+ ## Returns
16
+
17
+ **thread:** (`Promise<StorageThreadType | null>`): A promise that resolves to the thread associated with the given ID, or null if not found.
18
+
19
+ ### Related
20
+
21
+ - [Memory Class Reference](https://mastra.ai/reference/memory/memory-class)
22
+ - [Getting Started with Memory](https://mastra.ai/docs/memory/overview) (Covers threads concept)
23
+ - [createThread](https://mastra.ai/reference/memory/createThread)
24
+ - [listThreads](https://mastra.ai/reference/memory/listThreads)