@mastra/memory 1.0.0-beta.14 → 1.0.0-beta.15

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,54 @@
1
1
  # @mastra/memory
2
2
 
3
+ ## 1.0.0-beta.15
4
+
5
+ ### Minor Changes
6
+
7
+ - Added new `listThreads` method for flexible thread filtering across all storage adapters. ([#11832](https://github.com/mastra-ai/mastra/pull/11832))
8
+
9
+ **New Features**
10
+ - Filter threads by `resourceId`, `metadata`, or both (with AND logic for metadata key-value pairs)
11
+ - All filter parameters are optional, allowing you to list all threads or filter as needed
12
+ - Full pagination and sorting support
13
+
14
+ **Example Usage**
15
+
16
+ ```typescript
17
+ // List all threads
18
+ const allThreads = await memory.listThreads({});
19
+
20
+ // Filter by resourceId only
21
+ const userThreads = await memory.listThreads({
22
+ filter: { resourceId: 'user-123' },
23
+ });
24
+
25
+ // Filter by metadata only
26
+ const supportThreads = await memory.listThreads({
27
+ filter: { metadata: { category: 'support' } },
28
+ });
29
+
30
+ // Filter by both with pagination
31
+ const filteredThreads = await memory.listThreads({
32
+ filter: {
33
+ resourceId: 'user-123',
34
+ metadata: { priority: 'high', status: 'open' },
35
+ },
36
+ orderBy: { field: 'updatedAt', direction: 'DESC' },
37
+ page: 0,
38
+ perPage: 20,
39
+ });
40
+ ```
41
+
42
+ **Security Improvements**
43
+ - Added validation to prevent SQL injection via malicious metadata keys
44
+ - Added pagination parameter validation to prevent integer overflow attacks
45
+
46
+ ### Patch Changes
47
+
48
+ - Updated dependencies [[`ed3e3dd`](https://github.com/mastra-ai/mastra/commit/ed3e3ddec69d564fe2b125e083437f76331f1283), [`6833c69`](https://github.com/mastra-ai/mastra/commit/6833c69607418d257750bbcdd84638993d343539), [`47b1c16`](https://github.com/mastra-ai/mastra/commit/47b1c16a01c7ffb6765fe1e499b49092f8b7eba3), [`3a76a80`](https://github.com/mastra-ai/mastra/commit/3a76a80284cb71a0faa975abb3d4b2a9631e60cd), [`8538a0d`](https://github.com/mastra-ai/mastra/commit/8538a0d232619bf55dad7ddc2a8b0ca77c679a87), [`9312dcd`](https://github.com/mastra-ai/mastra/commit/9312dcd1c6f5b321929e7d382e763d95fdc030f5)]:
49
+ - @mastra/core@1.0.0-beta.25
50
+ - @mastra/schema-compat@1.0.0-beta.8
51
+
3
52
  ## 1.0.0-beta.14
4
53
 
5
54
  ### Patch Changes
@@ -33,4 +33,4 @@ docs/
33
33
  ## Version
34
34
 
35
35
  Package: @mastra/memory
36
- Version: 1.0.0-beta.14
36
+ Version: 1.0.0-beta.15
@@ -5,7 +5,7 @@ description: Documentation for @mastra/memory. Includes links to type definition
5
5
 
6
6
  # @mastra/memory Documentation
7
7
 
8
- > **Version**: 1.0.0-beta.14
8
+ > **Version**: 1.0.0-beta.15
9
9
  > **Package**: @mastra/memory
10
10
 
11
11
  ## Quick Navigation
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.0.0-beta.14",
2
+ "version": "1.0.0-beta.15",
3
3
  "package": "@mastra/memory",
4
4
  "exports": {
5
5
  "extractWorkingMemoryContent": {
@@ -125,6 +125,9 @@ const response = await memoryAgent.generate("What's my favorite color?", {
125
125
  });
126
126
  ```
127
127
 
128
+ > **Note:**
129
+ Each thread has an owner (`resourceId`) that cannot be changed after creation. Avoid reusing the same thread ID for threads with different owners, as this will cause errors when querying.
130
+
128
131
  To learn more about memory see the [Memory](../memory/overview) documentation.
129
132
 
130
133
  ## Using `RequestContext`
@@ -64,6 +64,67 @@ const handleDecline = async () => {
64
64
  };
65
65
  ```
66
66
 
67
+ ## Tool approval with generate()
68
+
69
+ Tool approval also works with the `generate()` method for non-streaming use cases. When using `generate()` with `requireToolApproval: true`, the method returns immediately when a tool requires approval instead of executing it.
70
+
71
+ ### How it works
72
+
73
+ When a tool requires approval during a `generate()` call, the response includes:
74
+
75
+ - `finishReason: 'suspended'` - indicates the agent is waiting for approval
76
+ - `suspendPayload` - contains tool call details (`toolCallId`, `toolName`, `args`)
77
+ - `runId` - needed to approve or decline the tool call
78
+
79
+ ### Approving tool calls
80
+
81
+ To approve a tool call with `generate()`, use the `approveToolCallGenerate` method:
82
+
83
+ ```typescript
84
+ const output = await agent.generate("Find user John", {
85
+ requireToolApproval: true,
86
+ });
87
+
88
+ if (output.finishReason === "suspended") {
89
+ console.log("Tool requires approval:", output.suspendPayload.toolName);
90
+ console.log("Arguments:", output.suspendPayload.args);
91
+
92
+ // Approve the tool call and get the final result
93
+ const result = await agent.approveToolCallGenerate({
94
+ runId: output.runId,
95
+ toolCallId: output.suspendPayload.toolCallId,
96
+ });
97
+
98
+ console.log("Final result:", result.text);
99
+ }
100
+ ```
101
+
102
+ ### Declining tool calls
103
+
104
+ To decline a tool call, use the `declineToolCallGenerate` method:
105
+
106
+ ```typescript
107
+ if (output.finishReason === "suspended") {
108
+ const result = await agent.declineToolCallGenerate({
109
+ runId: output.runId,
110
+ toolCallId: output.suspendPayload.toolCallId,
111
+ });
112
+
113
+ // Agent will respond acknowledging the declined tool
114
+ console.log(result.text);
115
+ }
116
+ ```
117
+
118
+ ### Stream vs Generate comparison
119
+
120
+ | Aspect | `stream()` | `generate()` |
121
+ |--------|-----------|--------------|
122
+ | Response type | Streaming chunks | Complete response |
123
+ | Approval detection | `tool-call-approval` chunk | `finishReason: 'suspended'` |
124
+ | Approve method | `approveToolCall({ runId })` | `approveToolCallGenerate({ runId, toolCallId })` |
125
+ | Decline method | `declineToolCall({ runId })` | `declineToolCallGenerate({ runId, toolCallId })` |
126
+ | Result | Stream to iterate | Full output object |
127
+
67
128
  ## Tool-level approval
68
129
 
69
130
  There are two types of tool call approval. The first uses `requireApproval`, which is a property on the tool definition, while `requireToolApproval` is a parameter passed to `agent.stream()`. The second uses `suspend` and lets the agent provide context or confirmation prompts so the user can decide whether the tool call should continue.
@@ -139,6 +139,21 @@ const stream = await agent.stream("message for agent", {
139
139
  > **Note:**
140
140
  [Studio](https://mastra.ai/docs/v1/getting-started/studio) automatically generates a thread and resource ID for you. Remember to to pass these explicitly when calling `stream` or `generate` yourself.
141
141
 
142
+ ### Thread and resource relationship
143
+
144
+ Each thread has an owner (its `resourceId`) that is set when the thread is created and cannot be changed. When you query a thread, you must use the correct owner's resource ID. Attempting to query a thread with a different resource ID will result in an error:
145
+
146
+ ```text
147
+ Thread with id <thread_id> is for resource with id <resource_a>
148
+ but resource <resource_b> was queried
149
+ ```
150
+
151
+ Note that while each thread has one owner, messages within that thread can have different `resourceId` values. This is used for message attribution and filtering (e.g., distinguishing between different agents in a multi-agent system, or filtering messages for analytics).
152
+
153
+ **Security:** Memory is a storage layer, not an authorization layer. Your application must implement access control before calling memory APIs. The `resourceId` parameter controls both validation and filtering - provide it to validate ownership and filter messages, or omit it for server-side access without validation.
154
+
155
+ To avoid accidentally reusing thread IDs across different owners, use UUIDs: `crypto.randomUUID()`
156
+
142
157
  ### Thread title generation
143
158
 
144
159
  Mastra can automatically generate descriptive thread titles based on the user's first message.
@@ -224,7 +224,7 @@ async function manageClones() {
224
224
  - [cloneThread](https://mastra.ai/reference/v1/memory/cloneThread)
225
225
  - [Memory Class Reference](https://mastra.ai/reference/v1/memory/memory-class)
226
226
  - [getThreadById](https://mastra.ai/reference/v1/memory/getThreadById)
227
- - [listThreadsByResourceId](https://mastra.ai/reference/v1/memory/listThreadsByResourceId)
227
+ - [listThreads](https://mastra.ai/reference/v1/memory/listThreads)
228
228
 
229
229
  ---
230
230
 
@@ -387,7 +387,7 @@ console.log(response.text);
387
387
  - [Memory Class Reference](https://mastra.ai/reference/v1/memory/memory-class)
388
388
  - [Getting Started with Memory](https://mastra.ai/docs/v1/memory/overview) (Covers threads concept)
389
389
  - [getThreadById](https://mastra.ai/reference/v1/memory/getThreadById)
390
- - [listThreadsByResourceId](https://mastra.ai/reference/v1/memory/listThreadsByResourceId)
390
+ - [listThreads](https://mastra.ai/reference/v1/memory/listThreads)
391
391
  - [recall](https://mastra.ai/reference/v1/memory/recall)
392
392
 
393
393
  ---
@@ -413,21 +413,70 @@ await memory?.getThreadById({ threadId: "thread-123" });
413
413
  - [Memory Class Reference](https://mastra.ai/reference/v1/memory/memory-class)
414
414
  - [Getting Started with Memory](https://mastra.ai/docs/v1/memory/overview) (Covers threads concept)
415
415
  - [createThread](https://mastra.ai/reference/v1/memory/createThread)
416
- - [listThreadsByResourceId](https://mastra.ai/reference/v1/memory/listThreadsByResourceId)
416
+ - [listThreads](https://mastra.ai/reference/v1/memory/listThreads)
417
417
 
418
418
  ---
419
419
 
420
- ## Reference: Memory.listThreadsByResourceId()
420
+ ## Reference: Memory.listThreads()
421
421
 
422
- > Documentation for the `Memory.listThreadsByResourceId()` method in Mastra, which retrieves threads associated with a specific resource ID with pagination support.
422
+ > Documentation for the `Memory.listThreads()` method in Mastra, which retrieves threads with optional filtering by resourceId and/or metadata.
423
423
 
424
- The `.listThreadsByResourceId()` method retrieves threads associated with a specific resource ID with pagination support.
424
+ The `listThreads()` method retrieves threads with pagination support and optional filtering by `resourceId`, `metadata`, or both.
425
425
 
426
- ## Usage Example
426
+ ## Usage Examples
427
+
428
+ ### List all threads with pagination
427
429
 
428
430
  ```typescript
429
- await memory.listThreadsByResourceId({
430
- resourceId: "user-123",
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
+ },
431
480
  page: 0,
432
481
  perPage: 10,
433
482
  });
@@ -438,8 +487,9 @@ await memory.listThreadsByResourceId({
438
487
  ## Returns
439
488
 
440
489
  The return object contains:
490
+
441
491
  - `threads`: Array of thread objects
442
- - `total`: Total number of threads for this resource
492
+ - `total`: Total number of threads matching the filter
443
493
  - `page`: Current page number (same as the input `page` parameter)
444
494
  - `perPage`: Items per page (same as the input `perPage` parameter)
445
495
  - `hasMore`: Boolean indicating if more results are available
@@ -456,9 +506,13 @@ let currentPage = 0;
456
506
  const perPage = 25;
457
507
  let hasMorePages = true;
458
508
 
509
+ // Fetch all active threads for a user, sorted by creation date
459
510
  while (hasMorePages) {
460
- const result = await memory?.listThreadsByResourceId({
461
- resourceId: "user-123",
511
+ const result = await memory?.listThreads({
512
+ filter: {
513
+ resourceId: "user-123",
514
+ metadata: { status: "active" },
515
+ },
462
516
  page: currentPage,
463
517
  perPage: perPage,
464
518
  orderBy: { field: "createdAt", direction: "ASC" },
@@ -478,6 +532,24 @@ while (hasMorePages) {
478
532
  }
479
533
  ```
480
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
+
481
553
  ## Related
482
554
 
483
555
  - [Memory Class Reference](https://mastra.ai/reference/v1/memory/memory-class)
@@ -609,7 +681,7 @@ export const agent = new Agent({
609
681
  - [createThread](https://mastra.ai/reference/v1/memory/createThread)
610
682
  - [recall](https://mastra.ai/reference/v1/memory/recall)
611
683
  - [getThreadById](https://mastra.ai/reference/v1/memory/getThreadById)
612
- - [listThreadsByResourceId](https://mastra.ai/reference/v1/memory/listThreadsByResourceId)
684
+ - [listThreads](https://mastra.ai/reference/v1/memory/listThreads)
613
685
  - [deleteMessages](https://mastra.ai/reference/v1/memory/deleteMessages)
614
686
  - [cloneThread](https://mastra.ai/reference/v1/memory/cloneThread)
615
687
  - [Clone Utility Methods](https://mastra.ai/reference/v1/memory/clone-utilities)
package/dist/index.cjs CHANGED
@@ -14722,9 +14722,9 @@ var Memory = class extends memory.MastraMemory {
14722
14722
  const memoryStore = await this.getMemoryStore();
14723
14723
  return memoryStore.getThreadById({ threadId });
14724
14724
  }
14725
- async listThreadsByResourceId(args) {
14725
+ async listThreads(args) {
14726
14726
  const memoryStore = await this.getMemoryStore();
14727
- return memoryStore.listThreadsByResourceId(args);
14727
+ return memoryStore.listThreads(args);
14728
14728
  }
14729
14729
  async handleWorkingMemoryFromMetadata({
14730
14730
  workingMemory,
@@ -15572,8 +15572,8 @@ ${template.content !== this.defaultWorkingMemoryTemplate ? `- Only store informa
15572
15572
  }
15573
15573
  targetResourceId = sourceThread.resourceId;
15574
15574
  }
15575
- const { threads } = await this.listThreadsByResourceId({
15576
- resourceId: targetResourceId,
15575
+ const { threads } = await this.listThreads({
15576
+ filter: { resourceId: targetResourceId },
15577
15577
  perPage: false
15578
15578
  // Get all threads
15579
15579
  });