@mastra/libsql 0.0.0-workflow-deno-20250616130925 → 0.0.0-workflow-timeout-issue-20260213181535

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 (81) hide show
  1. package/CHANGELOG.md +3186 -3
  2. package/LICENSE.md +12 -4
  3. package/README.md +32 -22
  4. package/dist/docs/SKILL.md +50 -0
  5. package/dist/docs/assets/SOURCE_MAP.json +6 -0
  6. package/dist/docs/references/docs-agents-agent-approval.md +377 -0
  7. package/dist/docs/references/docs-agents-agent-memory.md +212 -0
  8. package/dist/docs/references/docs-agents-network-approval.md +275 -0
  9. package/dist/docs/references/docs-agents-networks.md +290 -0
  10. package/dist/docs/references/docs-memory-memory-processors.md +316 -0
  11. package/dist/docs/references/docs-memory-message-history.md +260 -0
  12. package/dist/docs/references/docs-memory-overview.md +45 -0
  13. package/dist/docs/references/docs-memory-semantic-recall.md +272 -0
  14. package/dist/docs/references/docs-memory-storage.md +261 -0
  15. package/dist/docs/references/docs-memory-working-memory.md +400 -0
  16. package/dist/docs/references/docs-observability-overview.md +70 -0
  17. package/dist/docs/references/docs-observability-tracing-exporters-default.md +211 -0
  18. package/dist/docs/references/docs-rag-retrieval.md +521 -0
  19. package/dist/docs/references/docs-workflows-snapshots.md +238 -0
  20. package/dist/docs/references/guides-agent-frameworks-ai-sdk.md +140 -0
  21. package/dist/docs/references/reference-core-getMemory.md +50 -0
  22. package/dist/docs/references/reference-core-listMemory.md +56 -0
  23. package/dist/docs/references/reference-core-mastra-class.md +66 -0
  24. package/dist/docs/references/reference-memory-memory-class.md +147 -0
  25. package/dist/docs/references/reference-storage-composite.md +235 -0
  26. package/dist/docs/references/reference-storage-dynamodb.md +282 -0
  27. package/dist/docs/references/reference-storage-libsql.md +135 -0
  28. package/dist/docs/references/reference-vectors-libsql.md +305 -0
  29. package/dist/index.cjs +6477 -735
  30. package/dist/index.cjs.map +1 -0
  31. package/dist/index.d.ts +4 -6
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +6471 -737
  34. package/dist/index.js.map +1 -0
  35. package/dist/storage/db/index.d.ts +305 -0
  36. package/dist/storage/db/index.d.ts.map +1 -0
  37. package/dist/storage/db/utils.d.ts +68 -0
  38. package/dist/storage/db/utils.d.ts.map +1 -0
  39. package/dist/storage/domains/agents/index.d.ts +30 -0
  40. package/dist/storage/domains/agents/index.d.ts.map +1 -0
  41. package/dist/storage/domains/mcp-clients/index.d.ts +26 -0
  42. package/dist/storage/domains/mcp-clients/index.d.ts.map +1 -0
  43. package/dist/storage/domains/memory/index.d.ts +81 -0
  44. package/dist/storage/domains/memory/index.d.ts.map +1 -0
  45. package/dist/storage/domains/observability/index.d.ts +46 -0
  46. package/dist/storage/domains/observability/index.d.ts.map +1 -0
  47. package/dist/storage/domains/prompt-blocks/index.d.ts +25 -0
  48. package/dist/storage/domains/prompt-blocks/index.d.ts.map +1 -0
  49. package/dist/storage/domains/scorer-definitions/index.d.ts +26 -0
  50. package/dist/storage/domains/scorer-definitions/index.d.ts.map +1 -0
  51. package/dist/storage/domains/scores/index.d.ts +42 -0
  52. package/dist/storage/domains/scores/index.d.ts.map +1 -0
  53. package/dist/storage/domains/workflows/index.d.ts +47 -0
  54. package/dist/storage/domains/workflows/index.d.ts.map +1 -0
  55. package/dist/storage/index.d.ts +83 -0
  56. package/dist/storage/index.d.ts.map +1 -0
  57. package/dist/vector/filter.d.ts +29 -0
  58. package/dist/vector/filter.d.ts.map +1 -0
  59. package/dist/vector/index.d.ts +80 -0
  60. package/dist/vector/index.d.ts.map +1 -0
  61. package/dist/vector/prompt.d.ts +6 -0
  62. package/dist/vector/prompt.d.ts.map +1 -0
  63. package/dist/vector/sql-builder.d.ts +9 -0
  64. package/dist/vector/sql-builder.d.ts.map +1 -0
  65. package/package.json +34 -16
  66. package/.turbo/turbo-build.log +0 -23
  67. package/dist/_tsup-dts-rollup.d.cts +0 -295
  68. package/dist/_tsup-dts-rollup.d.ts +0 -295
  69. package/dist/index.d.cts +0 -6
  70. package/eslint.config.js +0 -6
  71. package/src/index.ts +0 -3
  72. package/src/storage/index.test.ts +0 -364
  73. package/src/storage/index.ts +0 -1131
  74. package/src/vector/filter.test.ts +0 -968
  75. package/src/vector/filter.ts +0 -117
  76. package/src/vector/index.test.ts +0 -1682
  77. package/src/vector/index.ts +0 -403
  78. package/src/vector/prompt.ts +0 -101
  79. package/src/vector/sql-builder.ts +0 -530
  80. package/tsconfig.json +0 -5
  81. package/vitest.config.ts +0 -11
package/LICENSE.md CHANGED
@@ -1,7 +1,15 @@
1
- Copyright 2025 Mastra AI, Inc.
1
+ # Apache License 2.0
2
2
 
3
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
3
+ Copyright (c) 2025 Kepler Software, Inc.
4
4
 
5
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
6
8
 
7
- THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # @mastra/pg
1
+ # @mastra/libsql
2
2
 
3
3
  SQLite implementation for Mastra, providing both vector similarity search and general storage capabilities with connection pooling and transaction support.
4
4
 
@@ -47,34 +47,41 @@ const results = await vectorStore.query({
47
47
  ### Storage
48
48
 
49
49
  ```typescript
50
- import { LibSQLStore } from '@mastra/pg';
50
+ import { LibSQLStore } from '@mastra/libsql';
51
51
 
52
52
  const store = new LibSQLStore({
53
+ id: 'libsql-storage',
53
54
  url: 'file:./my-db.db',
54
55
  });
55
56
 
56
57
  // Create a thread
57
58
  await store.saveThread({
58
- id: 'thread-123',
59
- resourceId: 'resource-456',
60
- title: 'My Thread',
61
- metadata: { key: 'value' },
59
+ thread: {
60
+ id: 'thread-123',
61
+ resourceId: 'resource-456',
62
+ title: 'My Thread',
63
+ metadata: { key: 'value' },
64
+ createdAt: new Date(),
65
+ },
62
66
  });
63
67
 
64
68
  // Add messages to thread
65
- await store.saveMessages([
66
- {
67
- id: 'msg-789',
68
- threadId: 'thread-123',
69
- role: 'user',
70
- type: 'text',
71
- content: [{ type: 'text', text: 'Hello' }],
72
- },
73
- ]);
69
+ await store.saveMessages({
70
+ messages: [
71
+ {
72
+ id: 'msg-789',
73
+ threadId: 'thread-123',
74
+ role: 'user',
75
+ content: { content: 'Hello' },
76
+ resourceId: 'resource-456',
77
+ createdAt: new Date(),
78
+ },
79
+ ],
80
+ });
74
81
 
75
82
  // Query threads and messages
76
- const savedThread = await store.getThread('thread-123');
77
- const messages = await store.getMessages('thread-123');
83
+ const savedThread = await store.getThreadById({ threadId: 'thread-123' });
84
+ const messages = await store.listMessages({ threadId: 'thread-123' });
78
85
  ```
79
86
 
80
87
  ## Configuration
@@ -124,6 +131,9 @@ Example filter:
124
131
  - `createIndex({indexName, dimension, metric?, indexConfig?, defineIndex?})`: Create a new table with vector support
125
132
  - `upsert({indexName, vectors, metadata?, ids?})`: Add or update vectors
126
133
  - `query({indexName, queryVector, topK?, filter?, includeVector?, minScore?})`: Search for similar vectors
134
+ - `updateVector({ indexName, id?, filter?, update })`: Update a single vector by ID or metadata filter
135
+ - `deleteVector({ indexName, id })`: Delete a single vector by ID
136
+ - `deleteVectors({ indexName, ids?, filter? })`: Delete multiple vectors by IDs or metadata filter
127
137
  - `defineIndex({indexName, metric?, indexConfig?})`: Define an index
128
138
  - `listIndexes()`: List all vector-enabled tables
129
139
  - `describeIndex(indexName)`: Get table statistics
@@ -132,11 +142,11 @@ Example filter:
132
142
 
133
143
  ## Storage Methods
134
144
 
135
- - `saveThread(thread)`: Create or update a thread
136
- - `getThread(threadId)`: Get a thread by ID
137
- - `deleteThread(threadId)`: Delete a thread and its messages
138
- - `saveMessages(messages)`: Save multiple messages in a transaction
139
- - `getMessages(threadId)`: Get all messages for a thread
145
+ - `saveThread({ thread })`: Create or update a thread
146
+ - `getThreadById({ threadId })`: Get a thread by ID
147
+ - `deleteThread({ threadId })`: Delete a thread and its messages
148
+ - `saveMessages({ messages })`: Save multiple messages in a transaction
149
+ - `listMessages({ threadId, perPage?, page? })`: Get messages for a thread with pagination
140
150
  - `deleteMessages(messageIds)`: Delete specific messages
141
151
 
142
152
  ## Related Links
@@ -0,0 +1,50 @@
1
+ ---
2
+ name: mastra-libsql
3
+ description: Documentation for @mastra/libsql. Use when working with @mastra/libsql APIs, configuration, or implementation.
4
+ metadata:
5
+ package: "@mastra/libsql"
6
+ version: "0.0.0-workflow-timeout-issue-20260213181535"
7
+ ---
8
+
9
+ ## When to use
10
+
11
+ Use this skill whenever you are working with @mastra/libsql to obtain the domain-specific knowledge.
12
+
13
+ ## How to use
14
+
15
+ Read the individual reference documents for detailed explanations and code examples.
16
+
17
+ ### Docs
18
+
19
+ - [Agent Approval](references/docs-agents-agent-approval.md) - Learn how to require approvals, suspend tool execution, and automatically resume suspended tools while keeping humans in control of agent workflows.
20
+ - [Agent Memory](references/docs-agents-agent-memory.md) - Learn how to add memory to agents to store message history and maintain context across interactions.
21
+ - [Network Approval](references/docs-agents-network-approval.md) - Learn how to require approvals, suspend execution, and resume suspended networks while keeping humans in control of agent network workflows.
22
+ - [Agent Networks](references/docs-agents-networks.md) - Learn how to coordinate multiple agents, workflows, and tools using agent networks for complex, non-deterministic task execution.
23
+ - [Memory Processors](references/docs-memory-memory-processors.md) - Learn how to use memory processors in Mastra to filter, trim, and transform messages before they're sent to the language model to manage context window limits.
24
+ - [Message History](references/docs-memory-message-history.md) - Learn how to configure message history in Mastra to store recent messages from the current conversation.
25
+ - [Memory overview](references/docs-memory-overview.md) - Learn how Mastra's memory system works with working memory, message history, semantic recall, and observational memory.
26
+ - [Semantic Recall](references/docs-memory-semantic-recall.md) - Learn how to use semantic recall in Mastra to retrieve relevant messages from past conversations using vector search and embeddings.
27
+ - [Storage](references/docs-memory-storage.md) - Configure storage for Mastra's memory system to persist conversations, workflows, and traces.
28
+ - [Working Memory](references/docs-memory-working-memory.md) - Learn how to configure working memory in Mastra to store persistent user data, preferences.
29
+ - [Observability Overview](references/docs-observability-overview.md) - Monitor and debug applications with Mastra's Observability features.
30
+ - [Default Exporter](references/docs-observability-tracing-exporters-default.md) - Store traces locally for development and debugging
31
+ - [Retrieval, Semantic Search, Reranking](references/docs-rag-retrieval.md) - Guide on retrieval processes in Mastra's RAG systems, including semantic search, filtering, and re-ranking.
32
+ - [Snapshots](references/docs-workflows-snapshots.md) - Learn how to save and resume workflow execution state with snapshots in Mastra
33
+
34
+ ### Guides
35
+
36
+ - [AI SDK](references/guides-agent-frameworks-ai-sdk.md) - Use Mastra processors and memory with the Vercel AI SDK
37
+
38
+ ### Reference
39
+
40
+ - [Reference: Mastra.getMemory()](references/reference-core-getMemory.md) - Documentation for the `Mastra.getMemory()` method in Mastra, which retrieves a registered memory instance by its registry key.
41
+ - [Reference: Mastra.listMemory()](references/reference-core-listMemory.md) - Documentation for the `Mastra.listMemory()` method in Mastra, which returns all registered memory instances.
42
+ - [Reference: Mastra Class](references/reference-core-mastra-class.md) - Documentation for the `Mastra` class in Mastra, the core entry point for managing agents, workflows, MCP servers, and server endpoints.
43
+ - [Reference: Memory Class](references/reference-memory-memory-class.md) - Documentation for the `Memory` class in Mastra, which provides a robust system for managing conversation history and thread-based message storage.
44
+ - [Reference: Composite Storage](references/reference-storage-composite.md) - Documentation for combining multiple storage backends in Mastra.
45
+ - [Reference: DynamoDB Storage](references/reference-storage-dynamodb.md) - Documentation for the DynamoDB storage implementation in Mastra, using a single-table design with ElectroDB.
46
+ - [Reference: libSQL Storage](references/reference-storage-libsql.md) - Documentation for the libSQL storage implementation in Mastra.
47
+ - [Reference: libSQL Vector Store](references/reference-vectors-libsql.md) - Documentation for the LibSQLVector class in Mastra, which provides vector search using libSQL with vector extensions.
48
+
49
+
50
+ Read [assets/SOURCE_MAP.json](assets/SOURCE_MAP.json) for source code references.
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": "0.0.0-workflow-timeout-issue-20260213181535",
3
+ "package": "@mastra/libsql",
4
+ "exports": {},
5
+ "modules": {}
6
+ }
@@ -0,0 +1,377 @@
1
+ # Agent Approval
2
+
3
+ Agents sometimes require the same [human-in-the-loop](https://mastra.ai/docs/workflows/human-in-the-loop) oversight used in workflows when calling tools that handle sensitive operations, like deleting resources or performing running long processes. With agent approval you can suspend a tool call and provide feedback to the user, or approve or decline a tool call based on targeted application conditions.
4
+
5
+ ## Tool call approval
6
+
7
+ Tool call approval can be enabled at the agent level and apply to every tool the agent uses, or at the tool level providing more granular control over individual tool calls.
8
+
9
+ ### Storage
10
+
11
+ Agent approval uses a snapshot to capture the state of the request. Ensure you've enabled a storage provider in your main Mastra instance. If storage isn't enabled you'll see an error relating to snapshot not found.
12
+
13
+ ```typescript
14
+ import { Mastra } from "@mastra/core/mastra";
15
+ import { LibSQLStore } from "@mastra/libsql";
16
+
17
+ export const mastra = new Mastra({
18
+ storage: new LibSQLStore({
19
+ id: "mastra-storage",
20
+ url: ":memory:"
21
+ })
22
+ });
23
+ ```
24
+
25
+ ## Agent-level approval
26
+
27
+ When calling an agent using `.stream()` set `requireToolApproval` to `true` which will prevent the agent from calling any of the tools defined in its configuration.
28
+
29
+ ```typescript
30
+ const stream = await agent.stream("What's the weather in London?", {
31
+ requireToolApproval: true
32
+ });
33
+ ```
34
+
35
+ ### Approving tool calls
36
+
37
+ To approve a tool call, access `approveToolCall` from the `agent`, passing in the `runId` of the stream. This will let the agent know its now OK to call its tools.
38
+
39
+ ```typescript
40
+ const handleApproval = async () => {
41
+ const approvedStream = await agent.approveToolCall({ runId: stream.runId });
42
+
43
+ for await (const chunk of approvedStream.textStream) {
44
+ process.stdout.write(chunk);
45
+ }
46
+ process.stdout.write("\n");
47
+ };
48
+ ```
49
+
50
+ ### Declining tool calls
51
+
52
+ To decline a tool call, access the `declineToolCall` from the `agent`. You will see the streamed response from the agent, but it won't call its tools.
53
+
54
+ ```typescript
55
+ const handleDecline = async () => {
56
+ const declinedStream = await agent.declineToolCall({ runId: stream.runId });
57
+
58
+ for await (const chunk of declinedStream.textStream) {
59
+ process.stdout.write(chunk);
60
+ }
61
+ process.stdout.write("\n");
62
+ };
63
+ ```
64
+
65
+ ## Tool approval with generate()
66
+
67
+ 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.
68
+
69
+ ### How it works
70
+
71
+ When a tool requires approval during a `generate()` call, the response includes:
72
+
73
+ - `finishReason: 'suspended'` - indicates the agent is waiting for approval
74
+ - `suspendPayload` - contains tool call details (`toolCallId`, `toolName`, `args`)
75
+ - `runId` - needed to approve or decline the tool call
76
+
77
+ ### Approving tool calls
78
+
79
+ To approve a tool call with `generate()`, use the `approveToolCallGenerate` method:
80
+
81
+ ```typescript
82
+ const output = await agent.generate("Find user John", {
83
+ requireToolApproval: true,
84
+ });
85
+
86
+ if (output.finishReason === "suspended") {
87
+ console.log("Tool requires approval:", output.suspendPayload.toolName);
88
+ console.log("Arguments:", output.suspendPayload.args);
89
+
90
+ // Approve the tool call and get the final result
91
+ const result = await agent.approveToolCallGenerate({
92
+ runId: output.runId,
93
+ toolCallId: output.suspendPayload.toolCallId,
94
+ });
95
+
96
+ console.log("Final result:", result.text);
97
+ }
98
+ ```
99
+
100
+ ### Declining tool calls
101
+
102
+ To decline a tool call, use the `declineToolCallGenerate` method:
103
+
104
+ ```typescript
105
+ if (output.finishReason === "suspended") {
106
+ const result = await agent.declineToolCallGenerate({
107
+ runId: output.runId,
108
+ toolCallId: output.suspendPayload.toolCallId,
109
+ });
110
+
111
+ // Agent will respond acknowledging the declined tool
112
+ console.log(result.text);
113
+ }
114
+ ```
115
+
116
+ ### Stream vs Generate comparison
117
+
118
+ | Aspect | `stream()` | `generate()` |
119
+ | ------------------ | ---------------------------- | ------------------------------------------------ |
120
+ | Response type | Streaming chunks | Complete response |
121
+ | Approval detection | `tool-call-approval` chunk | `finishReason: 'suspended'` |
122
+ | Approve method | `approveToolCall({ runId })` | `approveToolCallGenerate({ runId, toolCallId })` |
123
+ | Decline method | `declineToolCall({ runId })` | `declineToolCallGenerate({ runId, toolCallId })` |
124
+ | Result | Stream to iterate | Full output object |
125
+
126
+ ## Tool-level approval
127
+
128
+ 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.
129
+
130
+ ### Tool approval using `requireToolApproval`
131
+
132
+ In this approach, `requireApproval` is configured on the tool definition (shown below) rather than on the agent.
133
+
134
+ ```typescript
135
+ export const testTool = createTool({
136
+ id: "test-tool",
137
+ description: "Fetches weather for a location",
138
+ inputSchema: z.object({
139
+ location: z.string()
140
+ }),
141
+ outputSchema: z.object({
142
+ weather: z.string()
143
+ }),
144
+ resumeSchema: z.object({
145
+ approved: z.boolean()
146
+ }),
147
+ execute: async (inputData) => {
148
+ const response = await fetch(`https://wttr.in/${inputData.location}?format=3`);
149
+ const weather = await response.text();
150
+
151
+ return { weather };
152
+ },
153
+ requireApproval: true
154
+ });
155
+ ```
156
+
157
+ When `requireApproval` is true for a tool, the stream will include chunks of type `tool-call-approval` to indicate that the call is paused. To continue the call, invoke `resumeStream` with the required `resumeSchema` and the `runId`.
158
+
159
+ ```typescript
160
+ const stream = await agent.stream("What's the weather in London?");
161
+
162
+ for await (const chunk of stream.fullStream) {
163
+ if (chunk.type === "tool-call-approval") {
164
+ console.log("Approval required.");
165
+ }
166
+ }
167
+
168
+ const handleResume = async () => {
169
+ const resumedStream = await agent.resumeStream({ approved: true }, { runId: stream.runId });
170
+
171
+ for await (const chunk of resumedStream.textStream) {
172
+ process.stdout.write(chunk);
173
+ }
174
+ process.stdout.write("\n");
175
+ };
176
+ ```
177
+
178
+ ### Tool approval using `suspend`
179
+
180
+ With this approach, neither the agent nor the tool uses `requireApproval`. Instead, the tool implementation calls `suspend` to pause execution and return context or confirmation prompts to the user.
181
+
182
+ ```typescript
183
+ export const testToolB = createTool({
184
+ id: "test-tool-b",
185
+ description: "Fetches weather for a location",
186
+ inputSchema: z.object({
187
+ location: z.string()
188
+ }),
189
+ outputSchema: z.object({
190
+ weather: z.string()
191
+ }),
192
+ resumeSchema: z.object({
193
+ approved: z.boolean()
194
+ }),
195
+ suspendSchema: z.object({
196
+ reason: z.string()
197
+ }),
198
+ execute: async (inputData, context) => {
199
+ const { resumeData: { approved } = {}, suspend } = context?.agent ?? {};
200
+
201
+ if (!approved) {
202
+ return suspend?.({ reason: "Approval required." });
203
+ }
204
+
205
+ const response = await fetch(`https://wttr.in/${inputData.location}?format=3`);
206
+ const weather = await response.text();
207
+
208
+ return { weather };
209
+ }
210
+ });
211
+ ```
212
+
213
+ With this approach the stream will include a `tool-call-suspended` chunk, and the `suspendPayload` will contain the `reason` defined by the tool's `suspendSchema`. To continue the call, invoke `resumeStream` with the required `resumeSchema` and the `runId`.
214
+
215
+ ```typescript
216
+ const stream = await agent.stream("What's the weather in London?");
217
+
218
+ for await (const chunk of stream.fullStream) {
219
+ if (chunk.type === "tool-call-suspended") {
220
+ console.log(chunk.payload.suspendPayload);
221
+ }
222
+ }
223
+
224
+ const handleResume = async () => {
225
+ const resumedStream = await agent.resumeStream({ approved: true }, { runId: stream.runId });
226
+
227
+ for await (const chunk of resumedStream.textStream) {
228
+ process.stdout.write(chunk);
229
+ }
230
+ process.stdout.write("\n");
231
+ };
232
+ ```
233
+
234
+ ## Automatic tool resumption
235
+
236
+ When using tools that call `suspend()`, you can enable automatic resumption so the agent resumes suspended tools based on the user's next message. This creates a conversational flow where users provide the required information naturally, without your application needing to call `resumeStream()` explicitly.
237
+
238
+ ### Enabling auto-resume
239
+
240
+ Set `autoResumeSuspendedTools` to `true` in the agent's default options or when calling `stream()`:
241
+
242
+ ```typescript
243
+ import { Agent } from "@mastra/core/agent";
244
+ import { Memory } from "@mastra/memory";
245
+
246
+ // Option 1: In agent configuration
247
+ const agent = new Agent({
248
+ id: "my-agent",
249
+ name: "My Agent",
250
+ instructions: "You are a helpful assistant",
251
+ model: "openai/gpt-4o-mini",
252
+ tools: { weatherTool },
253
+ memory: new Memory(),
254
+ defaultOptions: {
255
+ autoResumeSuspendedTools: true,
256
+ },
257
+ });
258
+
259
+ // Option 2: Per-request
260
+ const stream = await agent.stream("What's the weather?", {
261
+ autoResumeSuspendedTools: true,
262
+ });
263
+ ```
264
+
265
+ ### How it works
266
+
267
+ When `autoResumeSuspendedTools` is enabled:
268
+
269
+ 1. A tool suspends execution by calling `suspend()` with a payload (e.g., requesting more information)
270
+
271
+ 2. The suspension is persisted to memory along with the conversation
272
+
273
+ 3. When the user sends their next message on the same thread, the agent:
274
+
275
+ - Detects the suspended tool from message history
276
+ - Extracts `resumeData` from the user's message based on the tool's `resumeSchema`
277
+ - Automatically resumes the tool with the extracted data
278
+
279
+ ### Example
280
+
281
+ ```typescript
282
+ import { createTool } from "@mastra/core/tools";
283
+ import { z } from "zod";
284
+
285
+ export const weatherTool = createTool({
286
+ id: "weather-info",
287
+ description: "Fetches weather information for a city",
288
+ suspendSchema: z.object({
289
+ message: z.string(),
290
+ }),
291
+ resumeSchema: z.object({
292
+ city: z.string(),
293
+ }),
294
+ execute: async (_inputData, context) => {
295
+ // Check if this is a resume with data
296
+ if (!context?.agent?.resumeData) {
297
+ // First call - suspend and ask for the city
298
+ return context?.agent?.suspend({
299
+ message: "What city do you want to know the weather for?",
300
+ });
301
+ }
302
+
303
+ // Resume call - city was extracted from user's message
304
+ const { city } = context.agent.resumeData;
305
+ const response = await fetch(`https://wttr.in/${city}?format=3`);
306
+ const weather = await response.text();
307
+
308
+ return { city, weather };
309
+ },
310
+ });
311
+
312
+ const agent = new Agent({
313
+ id: "my-agent",
314
+ name: "My Agent",
315
+ instructions: "You are a helpful assistant",
316
+ model: "openai/gpt-4o-mini",
317
+ tools: { weatherTool },
318
+ memory: new Memory(),
319
+ defaultOptions: {
320
+ autoResumeSuspendedTools: true,
321
+ },
322
+ });
323
+
324
+ const stream = await agent.stream("What's the weather like?");
325
+
326
+ for await (const chunk of stream.fullStream) {
327
+ if (chunk.type === "tool-call-suspended") {
328
+ console.log(chunk.payload.suspendPayload);
329
+ }
330
+ }
331
+
332
+ const handleResume = async () => {
333
+ const resumedStream = await agent.stream("San Francisco");
334
+
335
+ for await (const chunk of resumedStream.textStream) {
336
+ process.stdout.write(chunk);
337
+ }
338
+ process.stdout.write("\n");
339
+ };
340
+ ```
341
+
342
+ **Conversation flow:**
343
+
344
+ ```text
345
+ User: "What's the weather like?"
346
+ Agent: "What city do you want to know the weather for?"
347
+
348
+ User: "San Francisco"
349
+ Agent: "The weather in San Francisco is: San Francisco: ☀️ +72°F"
350
+ ```
351
+
352
+ The second message automatically resumes the suspended tool - the agent extracts `{ city: "San Francisco" }` from the user's message and passes it as `resumeData`.
353
+
354
+ ### Requirements
355
+
356
+ For automatic tool resumption to work:
357
+
358
+ - **Memory configured**: The agent needs memory to track suspended tools across messages
359
+ - **Same thread**: The follow-up message must use the same memory thread and resource identifiers
360
+ - **`resumeSchema` defined**: The tool must define a `resumeSchema` so the agent knows what data structure to extract from the user's message
361
+
362
+ ### Manual vs automatic resumption
363
+
364
+ | Approach | Use case |
365
+ | -------------------------------------- | ------------------------------------------------------------------------ |
366
+ | Manual (`resumeStream()`) | Programmatic control, webhooks, button clicks, external triggers |
367
+ | Automatic (`autoResumeSuspendedTools`) | Conversational flows where users provide resume data in natural language |
368
+
369
+ Both approaches work with the same tool definitions. Automatic resumption triggers only when suspended tools exist in the message history and the user sends a new message on the same thread.
370
+
371
+ ## Related
372
+
373
+ - [Using Tools](https://mastra.ai/docs/agents/using-tools)
374
+ - [Agent Overview](https://mastra.ai/docs/agents/overview)
375
+ - [Tools Overview](https://mastra.ai/docs/mcp/overview)
376
+ - [Agent Memory](https://mastra.ai/docs/agents/agent-memory)
377
+ - [Request Context](https://mastra.ai/docs/server/request-context)