@mastra/memory 1.5.0 → 1.5.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 (50) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/{chunk-DF7NDDSM.js → chunk-6PKWQ3GH.js} +28 -11
  3. package/dist/chunk-6PKWQ3GH.js.map +1 -0
  4. package/dist/{chunk-LLTHE64H.cjs → chunk-6XVTMLW4.cjs} +28 -11
  5. package/dist/chunk-6XVTMLW4.cjs.map +1 -0
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/{observational-memory-ZNTAIUGT.js → observational-memory-AJWSMZVP.js} +3 -3
  9. package/dist/{observational-memory-ZNTAIUGT.js.map → observational-memory-AJWSMZVP.js.map} +1 -1
  10. package/dist/{observational-memory-4PCXEZIS.cjs → observational-memory-Q5TO525O.cjs} +17 -17
  11. package/dist/{observational-memory-4PCXEZIS.cjs.map → observational-memory-Q5TO525O.cjs.map} +1 -1
  12. package/dist/processors/index.cjs +15 -15
  13. package/dist/processors/index.js +1 -1
  14. package/dist/processors/observational-memory/observational-memory.d.ts.map +1 -1
  15. package/dist/processors/observational-memory/token-counter.d.ts.map +1 -1
  16. package/package.json +7 -7
  17. package/dist/chunk-DF7NDDSM.js.map +0 -1
  18. package/dist/chunk-LLTHE64H.cjs.map +0 -1
  19. package/dist/docs/SKILL.md +0 -54
  20. package/dist/docs/assets/SOURCE_MAP.json +0 -103
  21. package/dist/docs/references/docs-agents-agent-approval.md +0 -377
  22. package/dist/docs/references/docs-agents-agent-memory.md +0 -212
  23. package/dist/docs/references/docs-agents-network-approval.md +0 -275
  24. package/dist/docs/references/docs-agents-networks.md +0 -290
  25. package/dist/docs/references/docs-memory-memory-processors.md +0 -316
  26. package/dist/docs/references/docs-memory-message-history.md +0 -260
  27. package/dist/docs/references/docs-memory-observational-memory.md +0 -246
  28. package/dist/docs/references/docs-memory-overview.md +0 -45
  29. package/dist/docs/references/docs-memory-semantic-recall.md +0 -272
  30. package/dist/docs/references/docs-memory-storage.md +0 -261
  31. package/dist/docs/references/docs-memory-working-memory.md +0 -400
  32. package/dist/docs/references/reference-core-getMemory.md +0 -50
  33. package/dist/docs/references/reference-core-listMemory.md +0 -56
  34. package/dist/docs/references/reference-memory-clone-utilities.md +0 -199
  35. package/dist/docs/references/reference-memory-cloneThread.md +0 -130
  36. package/dist/docs/references/reference-memory-createThread.md +0 -68
  37. package/dist/docs/references/reference-memory-getThreadById.md +0 -24
  38. package/dist/docs/references/reference-memory-listThreads.md +0 -145
  39. package/dist/docs/references/reference-memory-memory-class.md +0 -147
  40. package/dist/docs/references/reference-memory-observational-memory.md +0 -565
  41. package/dist/docs/references/reference-processors-token-limiter-processor.md +0 -113
  42. package/dist/docs/references/reference-storage-dynamodb.md +0 -282
  43. package/dist/docs/references/reference-storage-libsql.md +0 -135
  44. package/dist/docs/references/reference-storage-mongodb.md +0 -262
  45. package/dist/docs/references/reference-storage-postgresql.md +0 -529
  46. package/dist/docs/references/reference-storage-upstash.md +0 -160
  47. package/dist/docs/references/reference-vectors-libsql.md +0 -305
  48. package/dist/docs/references/reference-vectors-mongodb.md +0 -295
  49. package/dist/docs/references/reference-vectors-pg.md +0 -408
  50. package/dist/docs/references/reference-vectors-upstash.md +0 -294
@@ -1,400 +0,0 @@
1
- # Working Memory
2
-
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.
4
-
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.
6
-
7
- This is useful for maintaining ongoing state that's always relevant and should always be available to the agent.
8
-
9
- Working memory can persist at two different scopes:
10
-
11
- - **Resource-scoped** (default): Memory persists across all conversation threads for the same user
12
- - **Thread-scoped**: Memory is isolated per conversation thread
13
-
14
- **Important:** Switching between scopes means the agent won't see memory from the other scope - thread-scoped memory is completely separate from resource-scoped memory.
15
-
16
- ## Quick Start
17
-
18
- Here's a minimal example of setting up an agent with working memory:
19
-
20
- ```typescript
21
- import { Agent } from "@mastra/core/agent";
22
- import { Memory } from "@mastra/memory";
23
-
24
- // Create agent with working memory enabled
25
- const agent = new Agent({
26
- id: "personal-assistant",
27
- name: "PersonalAssistant",
28
- instructions: "You are a helpful personal assistant.",
29
- model: "openai/gpt-5.1",
30
- memory: new Memory({
31
- options: {
32
- workingMemory: {
33
- enabled: true,
34
- },
35
- },
36
- }),
37
- });
38
- ```
39
-
40
- ## How it Works
41
-
42
- Working memory is a block of Markdown text that the agent is able to update over time to store continuously relevant information:
43
-
44
- [YouTube video player](https://www.youtube-nocookie.com/embed/UMy_JHLf1n8)
45
-
46
- ## Memory Persistence Scopes
47
-
48
- Working memory can operate in two different scopes, allowing you to choose how memory persists across conversations:
49
-
50
- ### Resource-Scoped Memory (Default)
51
-
52
- By default, working memory persists across all conversation threads for the same user (resourceId), enabling persistent user memory:
53
-
54
- ```typescript
55
- const memory = new Memory({
56
- storage,
57
- options: {
58
- workingMemory: {
59
- enabled: true,
60
- scope: "resource", // Memory persists across all user threads
61
- template: `# User Profile
62
- - **Name**:
63
- - **Location**:
64
- - **Interests**:
65
- - **Preferences**:
66
- - **Long-term Goals**:
67
- `,
68
- },
69
- },
70
- });
71
- ```
72
-
73
- **Use cases:**
74
-
75
- - Personal assistants that remember user preferences
76
- - Customer service bots that maintain customer context
77
- - Educational applications that track student progress
78
-
79
- ### Usage with Agents
80
-
81
- When using resource-scoped memory, make sure to pass the `resource` parameter in the memory options:
82
-
83
- ```typescript
84
- // Resource-scoped memory requires resource
85
- const response = await agent.generate("Hello!", {
86
- memory: {
87
- thread: "conversation-123",
88
- resource: "user-alice-456", // Same user across different threads
89
- },
90
- });
91
- ```
92
-
93
- ### Thread-Scoped Memory
94
-
95
- Thread-scoped memory isolates working memory to individual conversation threads. Each thread maintains its own isolated memory:
96
-
97
- ```typescript
98
- const memory = new Memory({
99
- storage,
100
- options: {
101
- workingMemory: {
102
- enabled: true,
103
- scope: "thread", // Memory is isolated per thread
104
- template: `# User Profile
105
- - **Name**:
106
- - **Interests**:
107
- - **Current Goal**:
108
- `,
109
- },
110
- },
111
- });
112
- ```
113
-
114
- **Use cases:**
115
-
116
- - Different conversations about separate topics
117
- - Temporary or session-specific information
118
- - Workflows where each thread needs working memory but threads are ephemeral and not related to each other
119
-
120
- ## Storage Adapter Support
121
-
122
- Resource-scoped working memory requires specific storage adapters that support the `mastra_resources` table:
123
-
124
- ### Supported Storage Adapters
125
-
126
- - **libSQL** (`@mastra/libsql`)
127
- - **PostgreSQL** (`@mastra/pg`)
128
- - **Upstash** (`@mastra/upstash`)
129
- - **MongoDB** (`@mastra/mongodb`)
130
-
131
- ## Custom Templates
132
-
133
- Templates guide the agent on what information to track and update in working memory. While a default template is used if none is provided, you'll typically want to define a custom template tailored to your agent's specific use case to ensure it remembers the most relevant information.
134
-
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:
136
-
137
- ```typescript
138
- const memory = new Memory({
139
- options: {
140
- workingMemory: {
141
- enabled: true,
142
- template: `
143
- # User Profile
144
-
145
- ## Personal Info
146
-
147
- - Name:
148
- - Location:
149
- - Timezone:
150
-
151
- ## Preferences
152
-
153
- - Communication Style: [e.g., Formal, Casual]
154
- - Project Goal:
155
- - Key Deadlines:
156
- - [Deadline 1]: [Date]
157
- - [Deadline 2]: [Date]
158
-
159
- ## Session State
160
-
161
- - Last Task Discussed:
162
- - Open Questions:
163
- - [Question 1]
164
- - [Question 2]
165
- `,
166
- },
167
- },
168
- });
169
- ```
170
-
171
- ## Designing Effective Templates
172
-
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.
174
-
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.
180
-
181
- ### Alternative Template Styles
182
-
183
- Use a shorter single block if you only need a few items:
184
-
185
- ```typescript
186
- const basicMemory = new Memory({
187
- options: {
188
- workingMemory: {
189
- enabled: true,
190
- template: `User Facts:\n- Name:\n- Favorite Color:\n- Current Topic:`,
191
- },
192
- },
193
- });
194
- ```
195
-
196
- You can also store the key facts in a short paragraph format if you prefer a more narrative style:
197
-
198
- ```typescript
199
- const paragraphMemory = new Memory({
200
- options: {
201
- workingMemory: {
202
- enabled: true,
203
- template: `Important Details:\n\nKeep a short paragraph capturing the user's important facts (name, main goal, current task).`,
204
- },
205
- },
206
- });
207
- ```
208
-
209
- ## Structured Working Memory
210
-
211
- 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 [Zod](https://zod.dev/) schema. When using a schema, the agent will see and update working memory as a JSON object matching your schema.
212
-
213
- **Important:** You must specify either `template` or `schema`, but not both.
214
-
215
- ### Example: Schema-Based Working Memory
216
-
217
- ```typescript
218
- import { z } from "zod";
219
- import { Memory } from "@mastra/memory";
220
-
221
- const userProfileSchema = z.object({
222
- name: z.string().optional(),
223
- location: z.string().optional(),
224
- timezone: z.string().optional(),
225
- preferences: z
226
- .object({
227
- communicationStyle: z.string().optional(),
228
- projectGoal: z.string().optional(),
229
- deadlines: z.array(z.string()).optional(),
230
- })
231
- .optional(),
232
- });
233
-
234
- const memory = new Memory({
235
- options: {
236
- workingMemory: {
237
- enabled: true,
238
- schema: userProfileSchema,
239
- // template: ... (do not set)
240
- },
241
- },
242
- });
243
- ```
244
-
245
- When a schema is provided, the agent receives the working memory as a JSON object. For example:
246
-
247
- ```json
248
- {
249
- "name": "Sam",
250
- "location": "Berlin",
251
- "timezone": "CET",
252
- "preferences": {
253
- "communicationStyle": "Formal",
254
- "projectGoal": "Launch MVP",
255
- "deadlines": ["2025-07-01"]
256
- }
257
- }
258
- ```
259
-
260
- ### Merge Semantics for Schema-Based Memory
261
-
262
- 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.
263
-
264
- - **Object fields are deep merged:** Only provided fields are updated; others remain unchanged
265
- - **Set a field to `null` to delete it:** This explicitly removes the field from memory
266
- - **Arrays are replaced entirely:** When an array field is provided, it replaces the existing array (arrays are not merged element-by-element)
267
-
268
- ## Choosing Between Template and Schema
269
-
270
- - 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.
271
- - Use a **schema** if you need structured, type-safe data that can be validated and programmatically accessed as JSON. Schemas use **merge semantics** — the agent only provides fields to update, and existing fields are preserved.
272
- - Only one mode can be active at a time: setting both `template` and `schema` is not supported.
273
-
274
- ## Example: Multi-step Retention
275
-
276
- Below is a simplified view of how the `User Profile` template updates across a short user conversation:
277
-
278
- ```nohighlight
279
- # User Profile
280
-
281
- ## Personal Info
282
-
283
- - Name:
284
- - Location:
285
- - Timezone:
286
-
287
- --- After user says "My name is **Sam** and I'm from **Berlin**" ---
288
-
289
- # User Profile
290
- - Name: Sam
291
- - Location: Berlin
292
- - Timezone:
293
-
294
- --- After user adds "By the way I'm normally in **CET**" ---
295
-
296
- # User Profile
297
- - Name: Sam
298
- - Location: Berlin
299
- - Timezone: CET
300
- ```
301
-
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.
303
-
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.
305
-
306
- ## Setting Initial Working Memory
307
-
308
- 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.
309
-
310
- ### Setting Working Memory via Thread Metadata
311
-
312
- When creating a thread, you can provide initial working memory through the metadata's `workingMemory` key:
313
-
314
- ```typescript
315
- // Create a thread with initial working memory
316
- const thread = await memory.createThread({
317
- threadId: "thread-123",
318
- resourceId: "user-456",
319
- title: "Medical Consultation",
320
- metadata: {
321
- workingMemory: `# Patient Profile
322
- - Name: John Doe
323
- - Blood Type: O+
324
- - Allergies: Penicillin
325
- - Current Medications: None
326
- - Medical History: Hypertension (controlled)
327
- `,
328
- },
329
- });
330
-
331
- // The agent will now have access to this information in all messages
332
- await agent.generate("What's my blood type?", {
333
- memory: {
334
- thread: thread.id,
335
- resource: "user-456",
336
- },
337
- });
338
- // Response: "Your blood type is O+."
339
- ```
340
-
341
- ### Updating Working Memory Programmatically
342
-
343
- You can also update an existing thread's working memory:
344
-
345
- ```typescript
346
- // Update thread metadata to add/modify working memory
347
- await memory.updateThread({
348
- id: "thread-123",
349
- title: thread.title,
350
- metadata: {
351
- ...thread.metadata,
352
- workingMemory: `# Patient Profile
353
- - Name: John Doe
354
- - Blood Type: O+
355
- - Allergies: Penicillin, Ibuprofen // Updated
356
- - Current Medications: Lisinopril 10mg daily // Added
357
- - Medical History: Hypertension (controlled)
358
- `,
359
- },
360
- });
361
- ```
362
-
363
- ### Direct Memory Update
364
-
365
- Alternatively, use the `updateWorkingMemory` method directly:
366
-
367
- ```typescript
368
- await memory.updateWorkingMemory({
369
- threadId: "thread-123",
370
- resourceId: "user-456", // Required for resource-scoped memory
371
- workingMemory: "Updated memory content...",
372
- });
373
- ```
374
-
375
- ## Read-Only Working Memory
376
-
377
- 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:
378
-
379
- - **Routing agents** that need context but shouldn't update user profiles
380
- - **Sub agents** in a multi-agent system that should reference but not own the memory
381
-
382
- To enable read-only mode, set `readOnly: true` in the memory options:
383
-
384
- ```typescript
385
- const response = await agent.generate("What do you know about me?", {
386
- memory: {
387
- thread: "conversation-123",
388
- resource: "user-alice-456",
389
- options: {
390
- readOnly: true, // Working memory is provided but cannot be updated
391
- },
392
- },
393
- });
394
- ```
395
-
396
- ## Examples
397
-
398
- - [Working memory with template](https://github.com/mastra-ai/mastra/tree/main/examples/memory-with-template)
399
- - [Working memory with schema](https://github.com/mastra-ai/mastra/tree/main/examples/memory-with-schema)
400
- - [Per-resource working memory](https://github.com/mastra-ai/mastra/tree/main/examples/memory-per-resource-example) - Complete example showing resource-scoped memory persistence
@@ -1,50 +0,0 @@
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)
@@ -1,56 +0,0 @@
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)
@@ -1,199 +0,0 @@
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
- ```