@mastra/memory 1.0.0-beta.8 → 1.0.0

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.
@@ -0,0 +1,687 @@
1
+ # Memory API Reference
2
+
3
+ > API reference for memory - 6 entries
4
+
5
+
6
+ ---
7
+
8
+ ## Reference: Clone Utility Methods
9
+
10
+ > Documentation for utility methods to work with cloned threads in Mastra Memory.
11
+
12
+ 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.
13
+
14
+ ## isClone()
15
+
16
+ Checks whether a thread is a clone of another thread.
17
+
18
+ ### Usage
19
+
20
+ ```typescript
21
+ const isClonedThread = memory.isClone(thread);
22
+ ```
23
+
24
+ ### Parameters
25
+
26
+ ### Returns
27
+
28
+ ### Example
29
+
30
+ ```typescript
31
+ const thread = await memory.getThreadById({ threadId: "some-thread-id" });
32
+
33
+ if (memory.isClone(thread)) {
34
+ console.log("This thread was cloned from another thread");
35
+ } else {
36
+ console.log("This is an original thread");
37
+ }
38
+ ```
39
+
40
+ ---
41
+
42
+ ## getCloneMetadata()
43
+
44
+ Retrieves the clone metadata from a thread if it exists.
45
+
46
+ ### Usage
47
+
48
+ ```typescript
49
+ const metadata = memory.getCloneMetadata(thread);
50
+ ```
51
+
52
+ ### Parameters
53
+
54
+ ### Returns
55
+
56
+ Returns `ThreadCloneMetadata | null`:
57
+
58
+ ### Example
59
+
60
+ ```typescript
61
+ const thread = await memory.getThreadById({ threadId: "cloned-thread-id" });
62
+ const cloneInfo = memory.getCloneMetadata(thread);
63
+
64
+ if (cloneInfo) {
65
+ console.log(`Cloned from: ${cloneInfo.sourceThreadId}`);
66
+ console.log(`Cloned at: ${cloneInfo.clonedAt}`);
67
+ }
68
+ ```
69
+
70
+ ---
71
+
72
+ ## getSourceThread()
73
+
74
+ Retrieves the original source thread that a cloned thread was created from.
75
+
76
+ ### Usage
77
+
78
+ ```typescript
79
+ const sourceThread = await memory.getSourceThread(threadId);
80
+ ```
81
+
82
+ ### Parameters
83
+
84
+ ### Returns
85
+
86
+ ### Example
87
+
88
+ ```typescript
89
+ const sourceThread = await memory.getSourceThread("cloned-thread-id");
90
+
91
+ if (sourceThread) {
92
+ console.log(`Original thread title: ${sourceThread.title}`);
93
+ console.log(`Original thread created: ${sourceThread.createdAt}`);
94
+ }
95
+ ```
96
+
97
+ ---
98
+
99
+ ## listClones()
100
+
101
+ Lists all threads that were cloned from a specific source thread.
102
+
103
+ ### Usage
104
+
105
+ ```typescript
106
+ const clones = await memory.listClones(sourceThreadId);
107
+ ```
108
+
109
+ ### Parameters
110
+
111
+ ### Returns
112
+
113
+ ### Example
114
+
115
+ ```typescript
116
+ const clones = await memory.listClones("original-thread-id");
117
+
118
+ console.log(`Found ${clones.length} clones`);
119
+ for (const clone of clones) {
120
+ console.log(`- ${clone.id}: ${clone.title}`);
121
+ }
122
+ ```
123
+
124
+ ---
125
+
126
+ ## getCloneHistory()
127
+
128
+ Retrieves the full clone history chain for a thread, tracing back to the original.
129
+
130
+ ### Usage
131
+
132
+ ```typescript
133
+ const history = await memory.getCloneHistory(threadId);
134
+ ```
135
+
136
+ ### Parameters
137
+
138
+ ### Returns
139
+
140
+ ### Example
141
+
142
+ ```typescript
143
+ // If thread-c was cloned from thread-b, which was cloned from thread-a
144
+ const history = await memory.getCloneHistory("thread-c");
145
+
146
+ // history = [thread-a, thread-b, thread-c]
147
+ console.log(`Clone depth: ${history.length - 1}`);
148
+ console.log(`Original thread: ${history[0].id}`);
149
+ console.log(`Current thread: ${history[history.length - 1].id}`);
150
+
151
+ // Display the clone chain
152
+ for (let i = 0; i < history.length; i++) {
153
+ const prefix = i === 0 ? "Original" : `Clone ${i}`;
154
+ console.log(`${prefix}: ${history[i].title}`);
155
+ }
156
+ ```
157
+
158
+ ---
159
+
160
+ ## Complete Example
161
+
162
+ ```typescript title="src/clone-management.ts"
163
+ import { mastra } from "./mastra";
164
+
165
+ async function manageClones() {
166
+ const agent = mastra.getAgent("agent");
167
+ const memory = await agent.getMemory();
168
+
169
+ // Create an original conversation
170
+ const originalThread = await memory.createThread({
171
+ resourceId: "user-123",
172
+ title: "Original Conversation",
173
+ });
174
+
175
+ // Have a conversation...
176
+ await agent.generate("Hello! Let's discuss project options.", {
177
+ threadId: originalThread.id,
178
+ resourceId: "user-123",
179
+ });
180
+
181
+ // Create multiple branches (clones) to explore different paths
182
+ const { thread: optionA } = await memory.cloneThread({
183
+ sourceThreadId: originalThread.id,
184
+ title: "Option A - Conservative Approach",
185
+ });
186
+
187
+ const { thread: optionB } = await memory.cloneThread({
188
+ sourceThreadId: originalThread.id,
189
+ title: "Option B - Aggressive Approach",
190
+ });
191
+
192
+ // Check clone status
193
+ console.log(memory.isClone(originalThread)); // false
194
+ console.log(memory.isClone(optionA)); // true
195
+ console.log(memory.isClone(optionB)); // true
196
+
197
+ // Get clone metadata
198
+ const metadataA = memory.getCloneMetadata(optionA);
199
+ console.log(metadataA?.sourceThreadId); // originalThread.id
200
+
201
+ // List all clones of the original
202
+ const allClones = await memory.listClones(originalThread.id);
203
+ console.log(`Total alternatives: ${allClones.length}`); // 2
204
+
205
+ // Get source thread from a clone
206
+ const source = await memory.getSourceThread(optionA.id);
207
+ console.log(source?.id === originalThread.id); // true
208
+
209
+ // Create a deeper clone chain
210
+ const { thread: optionA2 } = await memory.cloneThread({
211
+ sourceThreadId: optionA.id,
212
+ title: "Option A - Variant 2",
213
+ });
214
+
215
+ // Get the full history
216
+ const history = await memory.getCloneHistory(optionA2.id);
217
+ // history = [originalThread, optionA, optionA2]
218
+ console.log(`Clone depth: ${history.length - 1}`); // 2
219
+ }
220
+ ```
221
+
222
+ ### Related
223
+
224
+ - [cloneThread](https://mastra.ai/reference/v1/memory/cloneThread)
225
+ - [Memory Class Reference](https://mastra.ai/reference/v1/memory/memory-class)
226
+ - [getThreadById](https://mastra.ai/reference/v1/memory/getThreadById)
227
+ - [listThreads](https://mastra.ai/reference/v1/memory/listThreads)
228
+
229
+ ---
230
+
231
+ ## Reference: Memory.cloneThread()
232
+
233
+ > Documentation for the `Memory.cloneThread()` method in Mastra, which creates a copy of a conversation thread with all its messages.
234
+
235
+ 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.
236
+
237
+ ## Usage Example
238
+
239
+ ```typescript
240
+ const { thread, clonedMessages } = await memory.cloneThread({
241
+ sourceThreadId: "original-thread-123",
242
+ });
243
+ ```
244
+
245
+ ## Parameters
246
+
247
+ ### Options Parameters
248
+
249
+ ### MessageFilter Parameters
250
+
251
+ ## Returns
252
+
253
+ ### Clone Metadata
254
+
255
+ The cloned thread's metadata includes a `clone` property with:
256
+
257
+ ## Extended Usage Example
258
+
259
+ ```typescript title="src/test-clone.ts"
260
+ import { mastra } from "./mastra";
261
+
262
+ const agent = mastra.getAgent("agent");
263
+ const memory = await agent.getMemory();
264
+
265
+ // Clone a thread with all messages
266
+ const { thread: fullClone } = await memory.cloneThread({
267
+ sourceThreadId: "original-thread-123",
268
+ title: "Alternative Conversation Path",
269
+ });
270
+
271
+ // Clone with a custom ID
272
+ const { thread: customIdClone } = await memory.cloneThread({
273
+ sourceThreadId: "original-thread-123",
274
+ newThreadId: "my-custom-clone-id",
275
+ });
276
+
277
+ // Clone only the last 5 messages
278
+ const { thread: partialClone, clonedMessages } = await memory.cloneThread({
279
+ sourceThreadId: "original-thread-123",
280
+ options: {
281
+ messageLimit: 5,
282
+ },
283
+ });
284
+
285
+ // Clone messages from a specific date range
286
+ const { thread: dateFilteredClone } = await memory.cloneThread({
287
+ sourceThreadId: "original-thread-123",
288
+ options: {
289
+ messageFilter: {
290
+ startDate: new Date("2024-01-01"),
291
+ endDate: new Date("2024-01-31"),
292
+ },
293
+ },
294
+ });
295
+
296
+ // Continue conversation on the cloned thread
297
+ const response = await agent.generate("Let's try a different approach", {
298
+ threadId: fullClone.id,
299
+ resourceId: fullClone.resourceId,
300
+ });
301
+ ```
302
+
303
+ ## Vector Embeddings
304
+
305
+ 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.
306
+
307
+ ```typescript
308
+ import { Memory } from "@mastra/memory";
309
+ import { LibSQLStore, LibSQLVector } from "@mastra/libsql";
310
+
311
+ const memory = new Memory({
312
+ storage: new LibSQLStore({ id: 'memory-store', url: "file:./memory.db" }),
313
+ vector: new LibSQLVector({ id: 'vector-store', url: "file:./vector.db" }),
314
+ embedder: embeddingModel,
315
+ options: {
316
+ semanticRecall: true,
317
+ },
318
+ });
319
+
320
+ // Clone will also create embeddings for cloned messages
321
+ const { thread } = await memory.cloneThread({
322
+ sourceThreadId: "original-thread",
323
+ });
324
+
325
+ // Semantic search works on the cloned thread
326
+ const results = await memory.recall({
327
+ threadId: thread.id,
328
+ vectorSearchString: "search query",
329
+ });
330
+ ```
331
+
332
+ ### Related
333
+
334
+ - [Memory Class Reference](https://mastra.ai/reference/v1/memory/memory-class)
335
+ - [createThread](https://mastra.ai/reference/v1/memory/createThread)
336
+ - [Clone Utility Methods](https://mastra.ai/reference/v1/memory/clone-utilities)
337
+ - [recall](https://mastra.ai/reference/v1/memory/recall)
338
+ - [Semantic Recall](https://mastra.ai/docs/v1/memory/semantic-recall)
339
+
340
+ ---
341
+
342
+ ## Reference: Memory.createThread()
343
+
344
+ > Documentation for the `Memory.createThread()` method in Mastra, which creates a new conversation thread in the memory system.
345
+
346
+ 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.
347
+
348
+ ## Usage Example
349
+
350
+ ```typescript
351
+ await memory?.createThread({ resourceId: "user-123" });
352
+ ```
353
+
354
+ ## Parameters
355
+
356
+ ## Returns
357
+
358
+ ## Extended usage example
359
+
360
+ ```typescript title="src/test-memory.ts"
361
+ import { mastra } from "./mastra";
362
+
363
+ const agent = mastra.getAgent("agent");
364
+ const memory = await agent.getMemory();
365
+
366
+ const thread = await memory?.createThread({
367
+ resourceId: "user-123",
368
+ title: "Memory Test Thread",
369
+ metadata: {
370
+ source: "test-script",
371
+ purpose: "memory-testing",
372
+ },
373
+ });
374
+
375
+ const response = await agent.generate("message for agent", {
376
+ memory: {
377
+ thread: thread!.id,
378
+ resource: thread!.resourceId,
379
+ },
380
+ });
381
+
382
+ console.log(response.text);
383
+ ```
384
+
385
+ ### Related
386
+
387
+ - [Memory Class Reference](https://mastra.ai/reference/v1/memory/memory-class)
388
+ - [Getting Started with Memory](https://mastra.ai/docs/v1/memory/overview) (Covers threads concept)
389
+ - [getThreadById](https://mastra.ai/reference/v1/memory/getThreadById)
390
+ - [listThreads](https://mastra.ai/reference/v1/memory/listThreads)
391
+ - [recall](https://mastra.ai/reference/v1/memory/recall)
392
+
393
+ ---
394
+
395
+ ## Reference: Memory.getThreadById()
396
+
397
+ > Documentation for the `Memory.getThreadById()` method in Mastra, which retrieves a specific thread by its ID.
398
+
399
+ The `.getThreadById()` method retrieves a specific thread by its ID.
400
+
401
+ ## Usage Example
402
+
403
+ ```typescript
404
+ await memory?.getThreadById({ threadId: "thread-123" });
405
+ ```
406
+
407
+ ## Parameters
408
+
409
+ ## Returns
410
+
411
+ ### Related
412
+
413
+ - [Memory Class Reference](https://mastra.ai/reference/v1/memory/memory-class)
414
+ - [Getting Started with Memory](https://mastra.ai/docs/v1/memory/overview) (Covers threads concept)
415
+ - [createThread](https://mastra.ai/reference/v1/memory/createThread)
416
+ - [listThreads](https://mastra.ai/reference/v1/memory/listThreads)
417
+
418
+ ---
419
+
420
+ ## Reference: Memory.listThreads()
421
+
422
+ > Documentation for the `Memory.listThreads()` method in Mastra, which retrieves threads with optional filtering by resourceId and/or metadata.
423
+
424
+ The `listThreads()` method retrieves threads with pagination support and optional filtering by `resourceId`, `metadata`, or both.
425
+
426
+ ## Usage Examples
427
+
428
+ ### List all threads with pagination
429
+
430
+ ```typescript
431
+ const result = await memory.listThreads({
432
+ page: 0,
433
+ perPage: 10,
434
+ });
435
+ ```
436
+
437
+ ### Fetch all threads without pagination
438
+
439
+ Use `perPage: false` to retrieve all matching threads at once.
440
+
441
+ > **Note:**
442
+
443
+ Generally speaking it's recommended to use pagination, especially for large datasets. Use this option cautiously.
444
+
445
+ ```typescript
446
+ const result = await memory.listThreads({
447
+ filter: { resourceId: "user-123" },
448
+ perPage: false,
449
+ });
450
+ ```
451
+
452
+ ### Filter by resourceId
453
+
454
+ ```typescript
455
+ const result = await memory.listThreads({
456
+ filter: { resourceId: "user-123" },
457
+ page: 0,
458
+ perPage: 10,
459
+ });
460
+ ```
461
+
462
+ ### Filter by metadata
463
+
464
+ ```typescript
465
+ const result = await memory.listThreads({
466
+ filter: { metadata: { category: "support", priority: "high" } },
467
+ page: 0,
468
+ perPage: 10,
469
+ });
470
+ ```
471
+
472
+ ### Combined filter (resourceId & metadata)
473
+
474
+ ```typescript
475
+ const result = await memory.listThreads({
476
+ filter: {
477
+ resourceId: "user-123",
478
+ metadata: { status: "active" },
479
+ },
480
+ page: 0,
481
+ perPage: 10,
482
+ });
483
+ ```
484
+
485
+ ## Parameters
486
+
487
+ ## Returns
488
+
489
+ The return object contains:
490
+
491
+ - `threads`: Array of thread objects
492
+ - `total`: Total number of threads matching the filter
493
+ - `page`: Current page number (same as the input `page` parameter)
494
+ - `perPage`: Items per page (same as the input `perPage` parameter)
495
+ - `hasMore`: Boolean indicating if more results are available
496
+
497
+ ## Extended usage example
498
+
499
+ ```typescript title="src/test-memory.ts"
500
+ import { mastra } from "./mastra";
501
+
502
+ const agent = mastra.getAgent("agent");
503
+ const memory = await agent.getMemory();
504
+
505
+ let currentPage = 0;
506
+ const perPage = 25;
507
+ let hasMorePages = true;
508
+
509
+ // Fetch all active threads for a user, sorted by creation date
510
+ while (hasMorePages) {
511
+ const result = await memory?.listThreads({
512
+ filter: {
513
+ resourceId: "user-123",
514
+ metadata: { status: "active" },
515
+ },
516
+ page: currentPage,
517
+ perPage: perPage,
518
+ orderBy: { field: "createdAt", direction: "ASC" },
519
+ });
520
+
521
+ if (!result) {
522
+ console.log("No threads");
523
+ break;
524
+ }
525
+
526
+ result.threads.forEach((thread) => {
527
+ console.log(`Thread: ${thread.id}, Created: ${thread.createdAt}`);
528
+ });
529
+
530
+ hasMorePages = result.hasMore;
531
+ currentPage++; // Move to next page
532
+ }
533
+ ```
534
+
535
+ ## Metadata Filtering
536
+
537
+ The metadata filter uses AND logic - all specified key-value pairs must match for a thread to be included in the results:
538
+
539
+ ```typescript
540
+ // This will only return threads where BOTH conditions are true:
541
+ // - category === 'support'
542
+ // - priority === 'high'
543
+ await memory.listThreads({
544
+ filter: {
545
+ metadata: {
546
+ category: "support",
547
+ priority: "high",
548
+ },
549
+ },
550
+ });
551
+ ```
552
+
553
+ ## Related
554
+
555
+ - [Memory Class Reference](https://mastra.ai/reference/v1/memory/memory-class)
556
+ - [Getting Started with Memory](https://mastra.ai/docs/v1/memory/overview) (Covers threads/resources concept)
557
+ - [createThread](https://mastra.ai/reference/v1/memory/createThread)
558
+ - [getThreadById](https://mastra.ai/reference/v1/memory/getThreadById)
559
+
560
+ ---
561
+
562
+ ## Reference: Memory Class
563
+
564
+ > Documentation for the `Memory` class in Mastra, which provides a robust system for managing conversation history and thread-based message storage.
565
+
566
+ The `Memory` class provides a robust system for managing conversation history and thread-based message storage in Mastra. It enables persistent storage of conversations, semantic search capabilities, and efficient message retrieval. You must configure a storage provider for conversation history, and if you enable semantic recall you will also need to provide a vector store and embedder.
567
+
568
+ ## Usage example
569
+
570
+ ```typescript title="src/mastra/agents/test-agent.ts"
571
+ import { Memory } from "@mastra/memory";
572
+ import { Agent } from "@mastra/core/agent";
573
+
574
+ export const agent = new Agent({
575
+ name: "test-agent",
576
+ instructions: "You are an agent with memory.",
577
+ model: "openai/gpt-5.1",
578
+ memory: new Memory({
579
+ options: {
580
+ workingMemory: {
581
+ enabled: true,
582
+ },
583
+ },
584
+ }),
585
+ });
586
+ ```
587
+
588
+ > To enable `workingMemory` on an agent, you’ll need a storage provider configured on your main Mastra instance. See [Mastra class](../core/mastra-class) for more information.
589
+
590
+ ## Constructor parameters
591
+
592
+ ### Options parameters
593
+
594
+ ## Returns
595
+
596
+ ## Extended usage example
597
+
598
+ ```typescript title="src/mastra/agents/test-agent.ts"
599
+ import { Memory } from "@mastra/memory";
600
+ import { Agent } from "@mastra/core/agent";
601
+ import { LibSQLStore, LibSQLVector } from "@mastra/libsql";
602
+
603
+ export const agent = new Agent({
604
+ name: "test-agent",
605
+ instructions: "You are an agent with memory.",
606
+ model: "openai/gpt-5.1",
607
+ memory: new Memory({
608
+ storage: new LibSQLStore({
609
+ id: 'test-agent-storage',
610
+ url: "file:./working-memory.db",
611
+ }),
612
+ vector: new LibSQLVector({
613
+ id: 'test-agent-vector',
614
+ url: "file:./vector-memory.db",
615
+ }),
616
+ options: {
617
+ lastMessages: 10,
618
+ semanticRecall: {
619
+ topK: 3,
620
+ messageRange: 2,
621
+ scope: "resource",
622
+ },
623
+ workingMemory: {
624
+ enabled: true,
625
+ },
626
+ generateTitle: true,
627
+ },
628
+ }),
629
+ });
630
+ ```
631
+
632
+ ## PostgreSQL with index configuration
633
+
634
+ ```typescript title="src/mastra/agents/pg-agent.ts"
635
+ import { Memory } from "@mastra/memory";
636
+ import { Agent } from "@mastra/core/agent";
637
+ import { ModelRouterEmbeddingModel } from "@mastra/core/llm";
638
+ import { PgStore, PgVector } from "@mastra/pg";
639
+
640
+ export const agent = new Agent({
641
+ name: "pg-agent",
642
+ instructions: "You are an agent with optimized PostgreSQL memory.",
643
+ model: "openai/gpt-5.1",
644
+ memory: new Memory({
645
+ storage: new PgStore({
646
+ id: 'pg-agent-storage',
647
+ connectionString: process.env.DATABASE_URL,
648
+ }),
649
+ vector: new PgVector({
650
+ id: 'pg-agent-vector',
651
+ connectionString: process.env.DATABASE_URL,
652
+ }),
653
+ embedder: new ModelRouterEmbeddingModel("openai/text-embedding-3-small"),
654
+ options: {
655
+ lastMessages: 20,
656
+ semanticRecall: {
657
+ topK: 5,
658
+ messageRange: 3,
659
+ scope: "resource",
660
+ indexConfig: {
661
+ type: "hnsw", // Use HNSW for better performance
662
+ metric: "dotproduct", // Optimal for OpenAI embeddings
663
+ m: 16, // Number of bi-directional links
664
+ efConstruction: 64, // Construction-time candidate list size
665
+ },
666
+ },
667
+ workingMemory: {
668
+ enabled: true,
669
+ },
670
+ },
671
+ }),
672
+ });
673
+ ```
674
+
675
+ ### Related
676
+
677
+ - [Getting Started with Memory](https://mastra.ai/docs/v1/memory/overview)
678
+ - [Semantic Recall](https://mastra.ai/docs/v1/memory/semantic-recall)
679
+ - [Working Memory](https://mastra.ai/docs/v1/memory/working-memory)
680
+ - [Memory Processors](https://mastra.ai/docs/v1/memory/memory-processors)
681
+ - [createThread](https://mastra.ai/reference/v1/memory/createThread)
682
+ - [recall](https://mastra.ai/reference/v1/memory/recall)
683
+ - [getThreadById](https://mastra.ai/reference/v1/memory/getThreadById)
684
+ - [listThreads](https://mastra.ai/reference/v1/memory/listThreads)
685
+ - [deleteMessages](https://mastra.ai/reference/v1/memory/deleteMessages)
686
+ - [cloneThread](https://mastra.ai/reference/v1/memory/cloneThread)
687
+ - [Clone Utility Methods](https://mastra.ai/reference/v1/memory/clone-utilities)