@mastra/libsql 1.0.0-beta.12 → 1.0.0-beta.13

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,51 @@
1
1
  # @mastra/libsql
2
2
 
3
+ ## 1.0.0-beta.13
4
+
5
+ ### Patch 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
+ - 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)]:
47
+ - @mastra/core@1.0.0-beta.25
48
+
3
49
  ## 1.0.0-beta.12
4
50
 
5
51
  ### Minor Changes
@@ -36,4 +36,4 @@ docs/
36
36
  ## Version
37
37
 
38
38
  Package: @mastra/libsql
39
- Version: 1.0.0-beta.12
39
+ Version: 1.0.0-beta.13
@@ -5,7 +5,7 @@ description: Documentation for @mastra/libsql. Includes links to type definition
5
5
 
6
6
  # @mastra/libsql Documentation
7
7
 
8
- > **Version**: 1.0.0-beta.12
8
+ > **Version**: 1.0.0-beta.13
9
9
  > **Package**: @mastra/libsql
10
10
 
11
11
  ## Quick Navigation
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.0.0-beta.12",
2
+ "version": "1.0.0-beta.13",
3
3
  "package": "@mastra/libsql",
4
4
  "exports": {},
5
5
  "modules": {}
@@ -90,6 +90,9 @@ export const memoryAgent = new Agent({
90
90
  });
91
91
  ```
92
92
 
93
+ > **Mastra Cloud Store limitation**
94
+ Agent-level storage is not supported when using [Mastra Cloud Store](https://mastra.ai/docs/v1/mastra-cloud/deployment#using-mastra-cloud-store). If you use Mastra Cloud Store, configure storage on the Mastra instance instead. This limitation does not apply if you bring your own database.
95
+
93
96
  ## Message history
94
97
 
95
98
  Include a `memory` object with both `resource` and `thread` to track message history during agent calls.
@@ -122,6 +125,9 @@ const response = await memoryAgent.generate("What's my favorite color?", {
122
125
  });
123
126
  ```
124
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
+
125
131
  To learn more about memory see the [Memory](../memory/overview) documentation.
126
132
 
127
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.
@@ -115,6 +115,9 @@ export const agent = new Agent({
115
115
 
116
116
  This is useful when different agents need to store data in separate databases for security, compliance, or organizational reasons.
117
117
 
118
+ > **Mastra Cloud Store limitation**
119
+ Agent-level storage is not supported when using [Mastra Cloud Store](https://mastra.ai/docs/v1/mastra-cloud/deployment#using-mastra-cloud-store). If you use Mastra Cloud Store, configure storage on the Mastra instance instead. This limitation does not apply if you bring your own database.
120
+
118
121
  ## Threads and resources
119
122
 
120
123
  Mastra organizes memory into threads using two identifiers:
@@ -136,6 +139,21 @@ const stream = await agent.stream("message for agent", {
136
139
  > **Note:**
137
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.
138
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
+
139
157
  ### Thread title generation
140
158
 
141
159
  Mastra can automatically generate descriptive thread titles based on the user's first message.
@@ -127,7 +127,7 @@ export const agent = new Agent({
127
127
  - [createThread](https://mastra.ai/reference/v1/memory/createThread)
128
128
  - [recall](https://mastra.ai/reference/v1/memory/recall)
129
129
  - [getThreadById](https://mastra.ai/reference/v1/memory/getThreadById)
130
- - [listThreadsByResourceId](https://mastra.ai/reference/v1/memory/listThreadsByResourceId)
130
+ - [listThreads](https://mastra.ai/reference/v1/memory/listThreads)
131
131
  - [deleteMessages](https://mastra.ai/reference/v1/memory/deleteMessages)
132
132
  - [cloneThread](https://mastra.ai/reference/v1/memory/cloneThread)
133
133
  - [Clone Utility Methods](https://mastra.ai/reference/v1/memory/clone-utilities)
package/dist/index.cjs CHANGED
@@ -2647,33 +2647,76 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
2647
2647
  );
2648
2648
  }
2649
2649
  }
2650
- async listThreadsByResourceId(args) {
2651
- const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
2652
- if (page < 0) {
2650
+ async listThreads(args) {
2651
+ const { page = 0, perPage: perPageInput, orderBy, filter } = args;
2652
+ try {
2653
+ this.validatePaginationInput(page, perPageInput ?? 100);
2654
+ } catch (error$1) {
2653
2655
  throw new error.MastraError(
2654
2656
  {
2655
- id: storage.createStorageErrorId("LIBSQL", "LIST_THREADS_BY_RESOURCE_ID", "INVALID_PAGE"),
2657
+ id: storage.createStorageErrorId("LIBSQL", "LIST_THREADS", "INVALID_PAGE"),
2656
2658
  domain: error.ErrorDomain.STORAGE,
2657
2659
  category: error.ErrorCategory.USER,
2658
- details: { page }
2660
+ details: { page, ...perPageInput !== void 0 && { perPage: perPageInput } }
2659
2661
  },
2660
- new Error("page must be >= 0")
2662
+ error$1 instanceof Error ? error$1 : new Error("Invalid pagination parameters")
2661
2663
  );
2662
2664
  }
2663
2665
  const perPage = storage.normalizePerPage(perPageInput, 100);
2666
+ try {
2667
+ this.validateMetadataKeys(filter?.metadata);
2668
+ } catch (error$1) {
2669
+ throw new error.MastraError(
2670
+ {
2671
+ id: storage.createStorageErrorId("LIBSQL", "LIST_THREADS", "INVALID_METADATA_KEY"),
2672
+ domain: error.ErrorDomain.STORAGE,
2673
+ category: error.ErrorCategory.USER,
2674
+ details: { metadataKeys: filter?.metadata ? Object.keys(filter.metadata).join(", ") : "" }
2675
+ },
2676
+ error$1 instanceof Error ? error$1 : new Error("Invalid metadata key")
2677
+ );
2678
+ }
2664
2679
  const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2665
2680
  const { field, direction } = this.parseOrderBy(orderBy);
2666
2681
  try {
2667
- const baseQuery = `FROM ${storage.TABLE_THREADS} WHERE resourceId = ?`;
2668
- const queryParams = [resourceId];
2682
+ const whereClauses = [];
2683
+ const queryParams = [];
2684
+ if (filter?.resourceId) {
2685
+ whereClauses.push("resourceId = ?");
2686
+ queryParams.push(filter.resourceId);
2687
+ }
2688
+ if (filter?.metadata && Object.keys(filter.metadata).length > 0) {
2689
+ for (const [key, value] of Object.entries(filter.metadata)) {
2690
+ if (value === null) {
2691
+ whereClauses.push(`json_extract(metadata, '$.${key}') IS NULL`);
2692
+ } else if (typeof value === "boolean") {
2693
+ whereClauses.push(`json_extract(metadata, '$.${key}') = ?`);
2694
+ queryParams.push(value ? 1 : 0);
2695
+ } else if (typeof value === "number") {
2696
+ whereClauses.push(`json_extract(metadata, '$.${key}') = ?`);
2697
+ queryParams.push(value);
2698
+ } else if (typeof value === "string") {
2699
+ whereClauses.push(`json_extract(metadata, '$.${key}') = ?`);
2700
+ queryParams.push(value);
2701
+ } else {
2702
+ throw new error.MastraError({
2703
+ id: storage.createStorageErrorId("LIBSQL", "LIST_THREADS", "INVALID_METADATA_VALUE"),
2704
+ domain: error.ErrorDomain.STORAGE,
2705
+ category: error.ErrorCategory.USER,
2706
+ text: `Metadata filter value for key "${key}" must be a scalar type (string, number, boolean, or null), got ${typeof value}`,
2707
+ details: { key, valueType: typeof value }
2708
+ });
2709
+ }
2710
+ }
2711
+ }
2712
+ const whereClause = whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
2713
+ const baseQuery = `FROM ${storage.TABLE_THREADS} ${whereClause}`;
2669
2714
  const mapRowToStorageThreadType = (row) => ({
2670
2715
  id: row.id,
2671
2716
  resourceId: row.resourceId,
2672
2717
  title: row.title,
2673
2718
  createdAt: new Date(row.createdAt),
2674
- // Convert string to Date
2675
2719
  updatedAt: new Date(row.updatedAt),
2676
- // Convert string to Date
2677
2720
  metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata) : row.metadata
2678
2721
  });
2679
2722
  const countResult = await this.#client.execute({
@@ -2704,12 +2747,18 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
2704
2747
  hasMore: perPageInput === false ? false : offset + perPage < total
2705
2748
  };
2706
2749
  } catch (error$1) {
2750
+ if (error$1 instanceof error.MastraError && error$1.category === error.ErrorCategory.USER) {
2751
+ throw error$1;
2752
+ }
2707
2753
  const mastraError = new error.MastraError(
2708
2754
  {
2709
- id: storage.createStorageErrorId("LIBSQL", "LIST_THREADS_BY_RESOURCE_ID", "FAILED"),
2755
+ id: storage.createStorageErrorId("LIBSQL", "LIST_THREADS", "FAILED"),
2710
2756
  domain: error.ErrorDomain.STORAGE,
2711
2757
  category: error.ErrorCategory.THIRD_PARTY,
2712
- details: { resourceId }
2758
+ details: {
2759
+ ...filter?.resourceId && { resourceId: filter.resourceId },
2760
+ hasMetadataFilter: !!filter?.metadata
2761
+ }
2713
2762
  },
2714
2763
  error$1
2715
2764
  );