@mastra/libsql 1.0.0-beta.9 → 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.
Files changed (44) hide show
  1. package/CHANGELOG.md +1164 -0
  2. package/dist/docs/README.md +39 -0
  3. package/dist/docs/SKILL.md +40 -0
  4. package/dist/docs/SOURCE_MAP.json +6 -0
  5. package/dist/docs/agents/01-agent-memory.md +166 -0
  6. package/dist/docs/agents/02-networks.md +292 -0
  7. package/dist/docs/agents/03-agent-approval.md +377 -0
  8. package/dist/docs/agents/04-network-approval.md +274 -0
  9. package/dist/docs/core/01-reference.md +151 -0
  10. package/dist/docs/guides/01-ai-sdk.md +141 -0
  11. package/dist/docs/memory/01-overview.md +76 -0
  12. package/dist/docs/memory/02-storage.md +233 -0
  13. package/dist/docs/memory/03-working-memory.md +390 -0
  14. package/dist/docs/memory/04-semantic-recall.md +233 -0
  15. package/dist/docs/memory/05-memory-processors.md +318 -0
  16. package/dist/docs/memory/06-reference.md +133 -0
  17. package/dist/docs/observability/01-overview.md +64 -0
  18. package/dist/docs/observability/02-default.md +177 -0
  19. package/dist/docs/rag/01-retrieval.md +548 -0
  20. package/dist/docs/storage/01-reference.md +542 -0
  21. package/dist/docs/vectors/01-reference.md +213 -0
  22. package/dist/docs/workflows/01-snapshots.md +240 -0
  23. package/dist/index.cjs +546 -107
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.js +543 -109
  26. package/dist/index.js.map +1 -1
  27. package/dist/storage/db/index.d.ts +42 -1
  28. package/dist/storage/db/index.d.ts.map +1 -1
  29. package/dist/storage/db/utils.d.ts +16 -1
  30. package/dist/storage/db/utils.d.ts.map +1 -1
  31. package/dist/storage/domains/memory/index.d.ts +3 -2
  32. package/dist/storage/domains/memory/index.d.ts.map +1 -1
  33. package/dist/storage/domains/observability/index.d.ts +23 -0
  34. package/dist/storage/domains/observability/index.d.ts.map +1 -1
  35. package/dist/storage/domains/scores/index.d.ts +0 -1
  36. package/dist/storage/domains/scores/index.d.ts.map +1 -1
  37. package/dist/storage/domains/workflows/index.d.ts +1 -0
  38. package/dist/storage/domains/workflows/index.d.ts.map +1 -1
  39. package/dist/storage/index.d.ts +10 -4
  40. package/dist/storage/index.d.ts.map +1 -1
  41. package/dist/vector/index.d.ts +6 -2
  42. package/dist/vector/index.d.ts.map +1 -1
  43. package/dist/vector/sql-builder.d.ts.map +1 -1
  44. package/package.json +9 -8
@@ -0,0 +1,213 @@
1
+ # Vectors API Reference
2
+
3
+ > API reference for vectors - 1 entries
4
+
5
+
6
+ ---
7
+
8
+ ## Reference: libSQL Vector Store
9
+
10
+ > Documentation for the LibSQLVector class in Mastra, which provides vector search using libSQL with vector extensions.
11
+
12
+ The libSQL storage implementation provides a SQLite-compatible vector search [libSQL](https://github.com/tursodatabase/libsql), a fork of SQLite with vector extensions, and [Turso](https://turso.tech/) with vector extensions, offering a lightweight and efficient vector database solution.
13
+ It's part of the `@mastra/libsql` package and offers efficient vector similarity search with metadata filtering.
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm install @mastra/libsql@beta
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ ```typescript
24
+ import { LibSQLVector } from "@mastra/libsql";
25
+
26
+ // Create a new vector store instance
27
+ const store = new LibSQLVector({
28
+ id: 'libsql-vector',
29
+ url: process.env.DATABASE_URL,
30
+ // Optional: for Turso cloud databases
31
+ authToken: process.env.DATABASE_AUTH_TOKEN,
32
+ });
33
+
34
+ // Create an index
35
+ await store.createIndex({
36
+ indexName: "myCollection",
37
+ dimension: 1536,
38
+ });
39
+
40
+ // Add vectors with metadata
41
+ const vectors = [[0.1, 0.2, ...], [0.3, 0.4, ...]];
42
+ const metadata = [
43
+ { text: "first document", category: "A" },
44
+ { text: "second document", category: "B" }
45
+ ];
46
+ await store.upsert({
47
+ indexName: "myCollection",
48
+ vectors,
49
+ metadata,
50
+ });
51
+
52
+ // Query similar vectors
53
+ const queryVector = [0.1, 0.2, ...];
54
+ const results = await store.query({
55
+ indexName: "myCollection",
56
+ queryVector,
57
+ topK: 10, // top K results
58
+ filter: { category: "A" } // optional metadata filter
59
+ });
60
+ ```
61
+
62
+ ## Constructor Options
63
+
64
+ ## Methods
65
+
66
+ ### createIndex()
67
+
68
+ Creates a new vector collection. The index name must start with a letter or underscore and can only contain letters, numbers, and underscores. The dimension must be a positive integer.
69
+
70
+ ### upsert()
71
+
72
+ Adds or updates vectors and their metadata in the index. Uses a transaction to ensure all vectors are inserted atomically - if any insert fails, the entire operation is rolled back.
73
+
74
+ ### query()
75
+
76
+ Searches for similar vectors with optional metadata filtering.
77
+
78
+ ### describeIndex()
79
+
80
+ Gets information about an index.
81
+
82
+ Returns:
83
+
84
+ ```typescript
85
+ interface IndexStats {
86
+ dimension: number;
87
+ count: number;
88
+ metric: "cosine" | "euclidean" | "dotproduct";
89
+ }
90
+ ```
91
+
92
+ ### deleteIndex()
93
+
94
+ Deletes an index and all its data.
95
+
96
+ ### listIndexes()
97
+
98
+ Lists all vector indexes in the database.
99
+
100
+ Returns: `Promise<string[]>`
101
+
102
+ ### truncateIndex()
103
+
104
+ Removes all vectors from an index while keeping the index structure.
105
+
106
+ ### updateVector()
107
+
108
+ Update a single vector by ID or by metadata filter. Either `id` or `filter` must be provided, but not both.
109
+
110
+ ### deleteVector()
111
+
112
+ Deletes a specific vector entry from an index by its ID.
113
+
114
+ ### deleteVectors()
115
+
116
+ Delete multiple vectors by IDs or by metadata filter. Either `ids` or `filter` must be provided, but not both.
117
+
118
+ ## Response Types
119
+
120
+ Query results are returned in this format:
121
+
122
+ ```typescript
123
+ interface QueryResult {
124
+ id: string;
125
+ score: number;
126
+ metadata: Record<string, any>;
127
+ vector?: number[]; // Only included if includeVector is true
128
+ }
129
+ ```
130
+
131
+ ## Error Handling
132
+
133
+ The store throws specific errors for different failure cases:
134
+
135
+ ```typescript
136
+ try {
137
+ await store.query({
138
+ indexName: "my-collection",
139
+ queryVector: queryVector,
140
+ });
141
+ } catch (error) {
142
+ // Handle specific error cases
143
+ if (error.message.includes("Invalid index name format")) {
144
+ console.error(
145
+ "Index name must start with a letter/underscore and contain only alphanumeric characters",
146
+ );
147
+ } else if (error.message.includes("Table not found")) {
148
+ console.error("The specified index does not exist");
149
+ } else {
150
+ console.error("Vector store error:", error.message);
151
+ }
152
+ }
153
+ ```
154
+
155
+ Common error cases include:
156
+
157
+ - Invalid index name format
158
+ - Invalid vector dimensions
159
+ - Table/index not found
160
+ - Database connection issues
161
+ - Transaction failures during upsert
162
+
163
+ ## Usage Example
164
+
165
+ ### Local embeddings with fastembed
166
+
167
+ Embeddings are numeric vectors used by memory's `semanticRecall` to retrieve related messages by meaning (not keywords). This setup uses `@mastra/fastembed` to generate vector embeddings.
168
+
169
+ Install `fastembed` to get started:
170
+
171
+ ```bash
172
+ npm install @mastra/fastembed@beta
173
+ ```
174
+
175
+ Add the following to your agent:
176
+
177
+ ```typescript title="src/mastra/agents/example-libsql-agent.ts"
178
+ import { Memory } from "@mastra/memory";
179
+ import { Agent } from "@mastra/core/agent";
180
+ import { LibSQLStore, LibSQLVector } from "@mastra/libsql";
181
+ import { fastembed } from "@mastra/fastembed";
182
+
183
+ export const libsqlAgent = new Agent({
184
+ id: "libsql-agent",
185
+ name: "libSQL Agent",
186
+ instructions:
187
+ "You are an AI agent with the ability to automatically recall memories from previous interactions.",
188
+ model: "openai/gpt-5.1",
189
+ memory: new Memory({
190
+ storage: new LibSQLStore({
191
+ id: 'libsql-agent-storage',
192
+ url: "file:libsql-agent.db",
193
+ }),
194
+ vector: new LibSQLVector({
195
+ id: 'libsql-agent-vector',
196
+ url: "file:libsql-agent.db",
197
+ }),
198
+ embedder: fastembed,
199
+ options: {
200
+ lastMessages: 10,
201
+ semanticRecall: {
202
+ topK: 3,
203
+ messageRange: 2,
204
+ },
205
+ generateTitle: true, // Explicitly enable automatic title generation
206
+ },
207
+ }),
208
+ });
209
+ ```
210
+
211
+ ## Related
212
+
213
+ - [Metadata Filters](../rag/metadata-filters)
@@ -0,0 +1,240 @@
1
+ > Learn how to save and resume workflow execution state with snapshots in Mastra
2
+
3
+ # Snapshots
4
+
5
+ In Mastra, a snapshot is a serializable representation of a workflow's complete execution state at a specific point in time. Snapshots capture all the information needed to resume a workflow from exactly where it left off, including:
6
+
7
+ - The current state of each step in the workflow
8
+ - The outputs of completed steps
9
+ - The execution path taken through the workflow
10
+ - Any suspended steps and their metadata
11
+ - The remaining retry attempts for each step
12
+ - Additional contextual data needed to resume execution
13
+
14
+ Snapshots are automatically created and managed by Mastra whenever a workflow is suspended, and are persisted to the configured storage system.
15
+
16
+ ## The role of snapshots in suspend and resume
17
+
18
+ Snapshots are the key mechanism enabling Mastra's suspend and resume capabilities. When a workflow step calls `await suspend()`:
19
+
20
+ 1. The workflow execution is paused at that exact point
21
+ 2. The current state of the workflow is captured as a snapshot
22
+ 3. The snapshot is persisted to storage
23
+ 4. The workflow step is marked as "suspended" with a status of `'suspended'`
24
+ 5. Later, when `resume()` is called on the suspended step, the snapshot is retrieved
25
+ 6. The workflow execution resumes from exactly where it left off
26
+
27
+ This mechanism provides a powerful way to implement human-in-the-loop workflows, handle rate limiting, wait for external resources, and implement complex branching workflows that may need to pause for extended periods.
28
+
29
+ ## Snapshot anatomy
30
+
31
+ Each snapshot includes the `runId`, input, step status (`success`, `suspended`, etc.), any suspend and resume payloads, and the final output. This ensures full context is available when resuming execution.
32
+
33
+ ```json
34
+ {
35
+ "runId": "34904c14-e79e-4a12-9804-9655d4616c50",
36
+ "status": "success",
37
+ "value": {},
38
+ "context": {
39
+ "input": {
40
+ "value": 100,
41
+ "user": "Michael",
42
+ "requiredApprovers": ["manager", "finance"]
43
+ },
44
+ "approval-step": {
45
+ "payload": {
46
+ "value": 100,
47
+ "user": "Michael",
48
+ "requiredApprovers": ["manager", "finance"]
49
+ },
50
+ "startedAt": 1758027577955,
51
+ "status": "success",
52
+ "suspendPayload": {
53
+ "message": "Workflow suspended",
54
+ "requestedBy": "Michael",
55
+ "approvers": ["manager", "finance"]
56
+ },
57
+ "suspendedAt": 1758027578065,
58
+ "resumePayload": { "confirm": true, "approver": "manager" },
59
+ "resumedAt": 1758027578517,
60
+ "output": { "value": 100, "approved": true },
61
+ "endedAt": 1758027578634
62
+ }
63
+ },
64
+ "activePaths": [],
65
+ "serializedStepGraph": [
66
+ {
67
+ "type": "step",
68
+ "step": {
69
+ "id": "approval-step",
70
+ "description": "Accepts a value, waits for confirmation"
71
+ }
72
+ }
73
+ ],
74
+ "suspendedPaths": {},
75
+ "waitingPaths": {},
76
+ "result": { "value": 100, "approved": true },
77
+ "requestContext": {},
78
+ "timestamp": 1758027578740
79
+ }
80
+ ```
81
+
82
+ ## How snapshots are saved and retrieved
83
+
84
+ Snapshots are saved to the configured storage system. By default, they use libSQL, but you can configure Upstash or PostgreSQL instead. Each snapshot is saved in the `workflow_snapshots` table and identified by the workflow's `runId`.
85
+
86
+ Read more about:
87
+
88
+ - [libSQL Storage](https://mastra.ai/reference/v1/storage/libsql)
89
+ - [Upstash Storage](https://mastra.ai/reference/v1/storage/upstash)
90
+ - [PostgreSQL Storage](https://mastra.ai/reference/v1/storage/postgresql)
91
+
92
+ ### Saving snapshots
93
+
94
+ When a workflow is suspended, Mastra automatically persists the workflow snapshot with these steps:
95
+
96
+ 1. The `suspend()` function in a step execution triggers the snapshot process
97
+ 2. The `WorkflowInstance.suspend()` method records the suspended machine
98
+ 3. `persistWorkflowSnapshot()` is called to save the current state
99
+ 4. The snapshot is serialized and stored in the configured database in the `workflow_snapshots` table
100
+ 5. The storage record includes the workflow name, run ID, and the serialized snapshot
101
+
102
+ ### Retrieving snapshots
103
+
104
+ When a workflow is resumed, Mastra retrieves the persisted snapshot with these steps:
105
+
106
+ 1. The `resume()` method is called with a specific step ID
107
+ 2. The snapshot is loaded from storage using `loadWorkflowSnapshot()`
108
+ 3. The snapshot is parsed and prepared for resumption
109
+ 4. The workflow execution is recreated with the snapshot state
110
+ 5. The suspended step is resumed, and execution continues
111
+
112
+ ```typescript
113
+ const storage = mastra.getStorage();
114
+ const workflowStore = await storage?.getStore('workflows');
115
+
116
+ const snapshot = await workflowStore?.loadWorkflowSnapshot({
117
+ runId: "<run-id>",
118
+ workflowName: "<workflow-id>",
119
+ });
120
+
121
+ console.log(snapshot);
122
+ ```
123
+
124
+ ## Storage options for snapshots
125
+
126
+ Snapshots are persisted using a `storage` instance configured on the `Mastra` class. This storage layer is shared across all workflows registered to that instance. Mastra supports multiple storage options for flexibility in different environments.
127
+
128
+ ```typescript title="src/mastra/index.ts"
129
+ import { Mastra } from "@mastra/core";
130
+ import { LibSQLStore } from "@mastra/libsql";
131
+ import { approvalWorkflow } from "./workflows";
132
+
133
+ export const mastra = new Mastra({
134
+ storage: new LibSQLStore({
135
+ id: 'mastra-storage',
136
+ url: ":memory:",
137
+ }),
138
+ workflows: { approvalWorkflow },
139
+ });
140
+ ```
141
+
142
+ - [libSQL Storage](https://mastra.ai/reference/v1/storage/libsql)
143
+ - [PostgreSQL Storage](https://mastra.ai/reference/v1/storage/postgresql)
144
+ - [MongoDB Storage](https://mastra.ai/reference/v1/storage/mongodb)
145
+ - [Upstash Storage](https://mastra.ai/reference/v1/storage/upstash)
146
+ - [Cloudflare D1](https://mastra.ai/reference/v1/storage/cloudflare-d1)
147
+ - [DynamoDB](https://mastra.ai/reference/v1/storage/dynamodb)
148
+ - [More storage providers](https://mastra.ai/docs/v1/memory/storage)
149
+
150
+ ## Best practices
151
+
152
+ 1. **Ensure Serializability**: Any data that needs to be included in the snapshot must be serializable (convertible to JSON).
153
+ 2. **Minimize Snapshot Size**: Avoid storing large data objects directly in the workflow context. Instead, store references to them (like IDs) and retrieve the data when needed.
154
+ 3. **Handle Resume Context Carefully**: When resuming a workflow, carefully consider what context to provide. This will be merged with the existing snapshot data.
155
+ 4. **Set Up Proper Monitoring**: Implement monitoring for suspended workflows, especially long-running ones, to ensure they are properly resumed.
156
+ 5. **Consider Storage Scaling**: For applications with many suspended workflows, ensure your storage solution is appropriately scaled.
157
+
158
+ ## Custom snapshot metadata
159
+
160
+ You can attach custom metadata when suspending a workflow by defining a `suspendSchema`. This metadata is stored in the snapshot and made available when the workflow is resumed.
161
+
162
+ ```typescript {30-34} title="src/mastra/workflows/test-workflow.ts"
163
+ import { createWorkflow, createStep } from "@mastra/core/workflows";
164
+ import { z } from "zod";
165
+
166
+ const approvalStep = createStep({
167
+ id: "approval-step",
168
+ description: "Accepts a value, waits for confirmation",
169
+ inputSchema: z.object({
170
+ value: z.number(),
171
+ user: z.string(),
172
+ requiredApprovers: z.array(z.string()),
173
+ }),
174
+ suspendSchema: z.object({
175
+ message: z.string(),
176
+ requestedBy: z.string(),
177
+ approvers: z.array(z.string()),
178
+ }),
179
+ resumeSchema: z.object({
180
+ confirm: z.boolean(),
181
+ approver: z.string(),
182
+ }),
183
+ outputSchema: z.object({
184
+ value: z.number(),
185
+ approved: z.boolean(),
186
+ }),
187
+ execute: async ({ inputData, resumeData, suspend }) => {
188
+ const { value, user, requiredApprovers } = inputData;
189
+ const { confirm } = resumeData ?? {};
190
+
191
+ if (!confirm) {
192
+ return await suspend({
193
+ message: "Workflow suspended",
194
+ requestedBy: user,
195
+ approvers: [...requiredApprovers],
196
+ });
197
+ }
198
+
199
+ return {
200
+ value,
201
+ approved: confirm,
202
+ };
203
+ },
204
+ });
205
+ ```
206
+
207
+ ### Providing resume data
208
+
209
+ Use `resumeData` to pass structured input when resuming a suspended step. It must match the step’s `resumeSchema`.
210
+
211
+ ```typescript {14-20}
212
+ const workflow = mastra.getWorkflow("approvalWorkflow");
213
+
214
+ const run = await workflow.createRun();
215
+
216
+ const result = await run.start({
217
+ inputData: {
218
+ value: 100,
219
+ user: "Michael",
220
+ requiredApprovers: ["manager", "finance"],
221
+ },
222
+ });
223
+
224
+ if (result.status === "suspended") {
225
+ const resumedResult = await run.resume({
226
+ step: "approval-step",
227
+ resumeData: {
228
+ confirm: true,
229
+ approver: "manager",
230
+ },
231
+ });
232
+ }
233
+ ```
234
+
235
+ ## Related
236
+
237
+ - [Control Flow](https://mastra.ai/docs/v1/workflows/control-flow)
238
+ - [Suspend & Resume](https://mastra.ai/docs/v1/workflows/suspend-and-resume)
239
+ - [Time Travel](https://mastra.ai/docs/v1/workflows/time-travel)
240
+ - [Human-in-the-loop](https://mastra.ai/docs/v1/workflows/human-in-the-loop)