@mastra/memory 0.0.0-bundle-recursion-20251030002519 → 0.0.0-bundle-version-20260121091645

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 (74) hide show
  1. package/CHANGELOG.md +1378 -4
  2. package/dist/_types/@internal_ai-sdk-v4/dist/index.d.ts +7549 -0
  3. package/dist/chunk-DGUM43GV.js +10 -0
  4. package/dist/chunk-DGUM43GV.js.map +1 -0
  5. package/dist/chunk-JEQ2X3Z6.cjs +12 -0
  6. package/dist/chunk-JEQ2X3Z6.cjs.map +1 -0
  7. package/dist/chunk-KMQS2YEC.js +79 -0
  8. package/dist/chunk-KMQS2YEC.js.map +1 -0
  9. package/dist/chunk-MMUHFOCG.js +79 -0
  10. package/dist/chunk-MMUHFOCG.js.map +1 -0
  11. package/dist/chunk-QY6BZOPJ.js +250 -0
  12. package/dist/chunk-QY6BZOPJ.js.map +1 -0
  13. package/dist/chunk-SG3GRV3O.cjs +84 -0
  14. package/dist/chunk-SG3GRV3O.cjs.map +1 -0
  15. package/dist/chunk-W72AYUIF.cjs +252 -0
  16. package/dist/chunk-W72AYUIF.cjs.map +1 -0
  17. package/dist/chunk-WC4XBMZT.js +250 -0
  18. package/dist/chunk-WC4XBMZT.js.map +1 -0
  19. package/dist/chunk-YMNW6DEN.cjs +252 -0
  20. package/dist/chunk-YMNW6DEN.cjs.map +1 -0
  21. package/dist/chunk-ZUQPUTTO.cjs +84 -0
  22. package/dist/chunk-ZUQPUTTO.cjs.map +1 -0
  23. package/dist/docs/README.md +36 -0
  24. package/dist/docs/SKILL.md +42 -0
  25. package/dist/docs/SOURCE_MAP.json +31 -0
  26. package/dist/docs/agents/01-agent-memory.md +166 -0
  27. package/dist/docs/agents/02-networks.md +292 -0
  28. package/dist/docs/agents/03-agent-approval.md +377 -0
  29. package/dist/docs/agents/04-network-approval.md +274 -0
  30. package/dist/docs/core/01-reference.md +114 -0
  31. package/dist/docs/memory/01-overview.md +76 -0
  32. package/dist/docs/memory/02-storage.md +233 -0
  33. package/dist/docs/memory/03-working-memory.md +390 -0
  34. package/dist/docs/memory/04-semantic-recall.md +233 -0
  35. package/dist/docs/memory/05-memory-processors.md +318 -0
  36. package/dist/docs/memory/06-reference.md +687 -0
  37. package/dist/docs/processors/01-reference.md +100 -0
  38. package/dist/docs/storage/01-reference.md +1135 -0
  39. package/dist/docs/vectors/01-reference.md +942 -0
  40. package/dist/index.cjs +14986 -261
  41. package/dist/index.cjs.map +1 -1
  42. package/dist/index.d.ts +167 -49
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +14948 -265
  45. package/dist/index.js.map +1 -1
  46. package/dist/token-6GSAFR2W-JV3TZR4M.cjs +63 -0
  47. package/dist/token-6GSAFR2W-JV3TZR4M.cjs.map +1 -0
  48. package/dist/token-6GSAFR2W-K2BTU23I.js +61 -0
  49. package/dist/token-6GSAFR2W-K2BTU23I.js.map +1 -0
  50. package/dist/token-6GSAFR2W-VLY2XUPA.js +61 -0
  51. package/dist/token-6GSAFR2W-VLY2XUPA.js.map +1 -0
  52. package/dist/token-6GSAFR2W-YCB5SK2Z.cjs +63 -0
  53. package/dist/token-6GSAFR2W-YCB5SK2Z.cjs.map +1 -0
  54. package/dist/token-util-NEHG7TUY-7IL6JUVY.cjs +10 -0
  55. package/dist/token-util-NEHG7TUY-7IL6JUVY.cjs.map +1 -0
  56. package/dist/token-util-NEHG7TUY-HF7KBP2H.cjs +10 -0
  57. package/dist/token-util-NEHG7TUY-HF7KBP2H.cjs.map +1 -0
  58. package/dist/token-util-NEHG7TUY-KSXDO2NO.js +8 -0
  59. package/dist/token-util-NEHG7TUY-KSXDO2NO.js.map +1 -0
  60. package/dist/token-util-NEHG7TUY-TIJ3LMSH.js +8 -0
  61. package/dist/token-util-NEHG7TUY-TIJ3LMSH.js.map +1 -0
  62. package/dist/tools/working-memory.d.ts +17 -24
  63. package/dist/tools/working-memory.d.ts.map +1 -1
  64. package/package.json +26 -34
  65. package/dist/processors/index.cjs +0 -165
  66. package/dist/processors/index.cjs.map +0 -1
  67. package/dist/processors/index.d.ts +0 -3
  68. package/dist/processors/index.d.ts.map +0 -1
  69. package/dist/processors/index.js +0 -158
  70. package/dist/processors/index.js.map +0 -1
  71. package/dist/processors/token-limiter.d.ts +0 -32
  72. package/dist/processors/token-limiter.d.ts.map +0 -1
  73. package/dist/processors/tool-call-filter.d.ts +0 -20
  74. package/dist/processors/tool-call-filter.d.ts.map +0 -1
@@ -0,0 +1,1135 @@
1
+ # Storage API Reference
2
+
3
+ > API reference for storage - 5 entries
4
+
5
+
6
+ ---
7
+
8
+ ## Reference: DynamoDB Storage
9
+
10
+ > Documentation for the DynamoDB storage implementation in Mastra, using a single-table design with ElectroDB.
11
+
12
+ The DynamoDB storage implementation provides a scalable and performant NoSQL database solution for Mastra, leveraging a single-table design pattern with [ElectroDB](https://electrodb.dev/).
13
+
14
+ ## Features
15
+
16
+ - Efficient single-table design for all Mastra storage needs
17
+ - Based on ElectroDB for type-safe DynamoDB access
18
+ - Support for AWS credentials, regions, and endpoints
19
+ - Compatible with AWS DynamoDB Local for development
20
+ - Stores Thread, Message, Trace, Eval, and Workflow data
21
+ - Optimized for serverless environments
22
+ - Configurable TTL (Time To Live) for automatic data expiration per entity type
23
+
24
+ ## Installation
25
+
26
+ ```bash
27
+ npm install @mastra/dynamodb@latest
28
+ ```
29
+
30
+ ## Prerequisites
31
+
32
+ Before using this package, you **must** create a DynamoDB table with a specific structure, including primary keys and Global Secondary Indexes (GSIs). This adapter expects the DynamoDB table and its GSIs to be provisioned externally.
33
+
34
+ Detailed instructions for setting up the table using AWS CloudFormation or AWS CDK are available in [TABLE_SETUP.md](https://github.com/mastra-ai/mastra/blob/main/stores/dynamodb/TABLE_SETUP.md). Please ensure your table is configured according to those instructions before proceeding.
35
+
36
+ ## Usage
37
+
38
+ ### Basic Usage
39
+
40
+ ```typescript
41
+ import { Memory } from "@mastra/memory";
42
+ import { DynamoDBStore } from "@mastra/dynamodb";
43
+
44
+ // Initialize the DynamoDB storage
45
+ const storage = new DynamoDBStore({
46
+ id: "dynamodb", // Unique identifier for this storage instance
47
+ config: {
48
+ tableName: "mastra-single-table", // Name of your DynamoDB table
49
+ region: "us-east-1", // Optional: AWS region, defaults to 'us-east-1'
50
+ // endpoint: "http://localhost:8000", // Optional: For local DynamoDB
51
+ // credentials: { accessKeyId: "YOUR_ACCESS_KEY", secretAccessKey: "YOUR_SECRET_KEY" } // Optional
52
+ },
53
+ });
54
+
55
+ // Example: Initialize Memory with DynamoDB storage
56
+ const memory = new Memory({
57
+ storage,
58
+ options: {
59
+ lastMessages: 10,
60
+ },
61
+ });
62
+ ```
63
+
64
+ ### Local Development with DynamoDB Local
65
+
66
+ For local development, you can use [DynamoDB Local](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html).
67
+
68
+ 1. **Run DynamoDB Local (e.g., using Docker):**
69
+
70
+ ```bash
71
+ docker run -p 8000:8000 amazon/dynamodb-local
72
+ ```
73
+
74
+ 2. **Configure `DynamoDBStore` to use the local endpoint:**
75
+
76
+ ```typescript
77
+ import { DynamoDBStore } from "@mastra/dynamodb";
78
+
79
+ const storage = new DynamoDBStore({
80
+ id: "dynamodb-local",
81
+ config: {
82
+ tableName: "mastra-single-table", // Ensure this table is created in your local DynamoDB
83
+ region: "localhost", // Can be any string for local, 'localhost' is common
84
+ endpoint: "http://localhost:8000",
85
+ // For DynamoDB Local, credentials are not typically required unless configured.
86
+ // If you've configured local credentials:
87
+ // credentials: { accessKeyId: "fakeMyKeyId", secretAccessKey: "fakeSecretAccessKey" }
88
+ },
89
+ });
90
+ ```
91
+
92
+ You will still need to create the table and GSIs in your local DynamoDB instance, for example, using the AWS CLI pointed to your local endpoint.
93
+
94
+ ## Parameters
95
+
96
+ ## TTL (Time To Live) Configuration
97
+
98
+ DynamoDB TTL allows you to automatically delete items after a specified time period. This is useful for:
99
+
100
+ - **Cost optimization**: Automatically remove old data to reduce storage costs
101
+ - **Data lifecycle management**: Implement retention policies for compliance
102
+ - **Performance**: Prevent tables from growing indefinitely
103
+ - **Privacy compliance**: Automatically purge personal data after specified periods
104
+
105
+ ### Enabling TTL
106
+
107
+ To use TTL, you must:
108
+
109
+ 1. **Configure TTL in DynamoDBStore** (shown below)
110
+ 2. **Enable TTL on your DynamoDB table** via AWS Console or CLI, specifying the attribute name (default: `ttl`)
111
+
112
+ ```typescript
113
+ import { DynamoDBStore } from "@mastra/dynamodb";
114
+
115
+ const storage = new DynamoDBStore({
116
+ name: "dynamodb",
117
+ config: {
118
+ tableName: "mastra-single-table",
119
+ region: "us-east-1",
120
+ ttl: {
121
+ // Messages expire after 30 days
122
+ message: {
123
+ enabled: true,
124
+ defaultTtlSeconds: 30 * 24 * 60 * 60, // 30 days
125
+ },
126
+ // Threads expire after 90 days
127
+ thread: {
128
+ enabled: true,
129
+ defaultTtlSeconds: 90 * 24 * 60 * 60, // 90 days
130
+ },
131
+ // Traces expire after 7 days with custom attribute name
132
+ trace: {
133
+ enabled: true,
134
+ attributeName: "expiresAt", // Custom TTL attribute
135
+ defaultTtlSeconds: 7 * 24 * 60 * 60, // 7 days
136
+ },
137
+ // Workflow snapshots don't expire
138
+ workflow_snapshot: {
139
+ enabled: false,
140
+ },
141
+ },
142
+ },
143
+ });
144
+ ```
145
+
146
+ ### Supported Entity Types
147
+
148
+ TTL can be configured for these entity types:
149
+
150
+ | Entity | Description |
151
+ |--------|-------------|
152
+ | `thread` | Conversation threads |
153
+ | `message` | Messages within threads |
154
+ | `trace` | Observability traces |
155
+ | `eval` | Evaluation results |
156
+ | `workflow_snapshot` | Workflow state snapshots |
157
+ | `resource` | User/resource data |
158
+ | `score` | Scoring results |
159
+
160
+ ### TTL Entity Configuration
161
+
162
+ Each entity type accepts the following configuration:
163
+
164
+ ### Enabling TTL on Your DynamoDB Table
165
+
166
+ After configuring TTL in your code, you must enable TTL on the DynamoDB table itself:
167
+
168
+ **Using AWS CLI:**
169
+
170
+ ```bash
171
+ aws dynamodb update-time-to-live \
172
+ --table-name mastra-single-table \
173
+ --time-to-live-specification "Enabled=true, AttributeName=ttl"
174
+ ```
175
+
176
+ **Using AWS Console:**
177
+
178
+ 1. Go to the DynamoDB console
179
+ 2. Select your table
180
+ 3. Go to "Additional settings" tab
181
+ 4. Under "Time to Live (TTL)", click "Manage TTL"
182
+ 5. Enable TTL and specify the attribute name (default: `ttl`)
183
+
184
+ > **Note**: DynamoDB deletes expired items within 48 hours after expiration. Items remain queryable until actually deleted.
185
+
186
+ ## AWS IAM Permissions
187
+
188
+ The IAM role or user executing the code needs appropriate permissions to interact with the specified DynamoDB table and its indexes. Below is a sample policy. Replace `${YOUR_TABLE_NAME}` with your actual table name and `${YOUR_AWS_REGION}` and `${YOUR_AWS_ACCOUNT_ID}` with appropriate values.
189
+
190
+ ```json
191
+ {
192
+ "Version": "2012-10-17",
193
+ "Statement": [
194
+ {
195
+ "Effect": "Allow",
196
+ "Action": [
197
+ "dynamodb:DescribeTable",
198
+ "dynamodb:GetItem",
199
+ "dynamodb:PutItem",
200
+ "dynamodb:UpdateItem",
201
+ "dynamodb:DeleteItem",
202
+ "dynamodb:Query",
203
+ "dynamodb:Scan",
204
+ "dynamodb:BatchGetItem",
205
+ "dynamodb:BatchWriteItem"
206
+ ],
207
+ "Resource": [
208
+ "arn:aws:dynamodb:${YOUR_AWS_REGION}:${YOUR_AWS_ACCOUNT_ID}:table/${YOUR_TABLE_NAME}",
209
+ "arn:aws:dynamodb:${YOUR_AWS_REGION}:${YOUR_AWS_ACCOUNT_ID}:table/${YOUR_TABLE_NAME}/index/*"
210
+ ]
211
+ }
212
+ ]
213
+ }
214
+ ```
215
+
216
+ ## Key Considerations
217
+
218
+ Before diving into the architectural details, keep these key points in mind when working with the DynamoDB storage adapter:
219
+
220
+ - **External Table Provisioning:** This adapter _requires_ you to create and configure the DynamoDB table and its Global Secondary Indexes (GSIs) yourself, prior to using the adapter. Follow the guide in [TABLE_SETUP.md](https://github.com/mastra-ai/mastra/blob/main/stores/dynamodb/TABLE_SETUP.md).
221
+ - **Single-Table Design:** All Mastra data (threads, messages, etc.) is stored in one DynamoDB table. This is a deliberate design choice optimized for DynamoDB, differing from relational database approaches.
222
+ - **Understanding GSIs:** Familiarity with how the GSIs are structured (as per `TABLE_SETUP.md`) is important for understanding data retrieval and potential query patterns.
223
+ - **ElectroDB:** The adapter uses ElectroDB to manage interactions with DynamoDB, providing a layer of abstraction and type safety over raw DynamoDB operations.
224
+
225
+ ## Architectural Approach
226
+
227
+ This storage adapter utilizes a **single-table design pattern** leveraging [ElectroDB](https://electrodb.dev/), a common and recommended approach for DynamoDB. This differs architecturally from relational database adapters (like `@mastra/pg` or `@mastra/libsql`) that typically use multiple tables, each dedicated to a specific entity (threads, messages, etc.).
228
+
229
+ Key aspects of this approach:
230
+
231
+ - **DynamoDB Native:** The single-table design is optimized for DynamoDB's key-value and query capabilities, often leading to better performance and scalability compared to mimicking relational models.
232
+ - **External Table Management:** Unlike some adapters that might offer helper functions to create tables via code, this adapter **expects the DynamoDB table and its associated Global Secondary Indexes (GSIs) to be provisioned externally** before use. Please refer to [TABLE_SETUP.md](https://github.com/mastra-ai/mastra/blob/main/stores/dynamodb/TABLE_SETUP.md) for detailed instructions using tools like AWS CloudFormation or CDK. The adapter focuses solely on interacting with the pre-existing table structure.
233
+ - **Consistency via Interface:** While the underlying storage model differs, this adapter adheres to the same `MastraStorage` interface as other adapters, ensuring it can be used interchangeably within the Mastra `Memory` component.
234
+
235
+ ### Mastra Data in the Single Table
236
+
237
+ Within the single DynamoDB table, different Mastra data entities (such as Threads, Messages, Traces, Evals, and Workflows) are managed and distinguished using ElectroDB. ElectroDB defines specific models for each entity type, which include unique key structures and attributes. This allows the adapter to store and retrieve diverse data types efficiently within the same table.
238
+
239
+ For example, a `Thread` item might have a primary key like `THREAD#<threadId>`, while a `Message` item belonging to that thread might use `THREAD#<threadId>` as a partition key and `MESSAGE#<messageId>` as a sort key. The Global Secondary Indexes (GSIs), detailed in `TABLE_SETUP.md`, are strategically designed to support common access patterns across these different entities, such as fetching all messages for a thread or querying traces associated with a particular workflow.
240
+
241
+ ### Advantages of Single-Table Design
242
+
243
+ This implementation uses a single-table design pattern with ElectroDB, which offers several advantages within the context of DynamoDB:
244
+
245
+ 1. **Lower cost (potentially):** Fewer tables can simplify Read/Write Capacity Unit (RCU/WCU) provisioning and management, especially with on-demand capacity.
246
+ 2. **Better performance:** Related data can be co-located or accessed efficiently through GSIs, enabling fast lookups for common access patterns.
247
+ 3. **Simplified administration:** Fewer distinct tables to monitor, back up, and manage.
248
+ 4. **Reduced complexity in access patterns:** ElectroDB helps manage the complexity of item types and access patterns on a single table.
249
+ 5. **Transaction support:** DynamoDB transactions can be used across different "entity" types stored within the same table if needed.
250
+
251
+ ---
252
+
253
+ ## Reference: libSQL Storage
254
+
255
+ > Documentation for the libSQL storage implementation in Mastra.
256
+
257
+ [libSQL](https://docs.turso.tech/libsql) is an open-source, SQLite-compatible database that supports both local and remote deployments. It can be used to store message history, workflow snapshots, traces, and eval scores.
258
+
259
+ For vectors like semantic recall or traditional RAG, use [libSQL Vector](https://mastra.ai/reference/vectors/libsql) which covers embeddings and vector search.
260
+
261
+ ## Installation
262
+
263
+ Storage providers must be installed as separate packages:
264
+
265
+ ```bash
266
+ npm install @mastra/libsql@latest
267
+ ```
268
+
269
+ ## Usage
270
+
271
+ ```typescript
272
+ import { LibSQLStore } from "@mastra/libsql";
273
+ import { Mastra } from "@mastra/core";
274
+
275
+ const mastra = new Mastra({
276
+ storage: new LibSQLStore({
277
+ id: 'libsql-storage',
278
+ url: "file:./storage.db",
279
+ }),
280
+ });
281
+ ```
282
+
283
+ Agent-level file storage:
284
+
285
+ ```typescript
286
+ import { Memory } from "@mastra/memory";
287
+ import { Agent } from "@mastra/core/agent";
288
+ import { LibSQLStore } from "@mastra/libsql";
289
+
290
+ export const agent = new Agent({
291
+ id: "example-agent",
292
+ memory: new Memory({
293
+ storage: new LibSQLStore({
294
+ id: 'libsql-storage',
295
+ url: "file:./agent.db",
296
+ }),
297
+ }),
298
+ });
299
+ ```
300
+
301
+ > **Note:**
302
+ File storage doesn't work with serverless platforms that have ephemeral file systems. For serverless deployments, use [Turso](https://turso.tech) or a different database engine.
303
+
304
+ Production with remote database:
305
+
306
+ ```typescript
307
+ storage: new LibSQLStore({
308
+ id: 'libsql-storage',
309
+ url: "libsql://your-db-name.aws-ap-northeast-1.turso.io",
310
+ authToken: process.env.TURSO_AUTH_TOKEN,
311
+ })
312
+ ```
313
+
314
+ For local development and testing, you can store data in memory:
315
+
316
+ ```typescript
317
+ storage: new LibSQLStore({
318
+ id: 'libsql-storage',
319
+ url: ":memory:",
320
+ })
321
+ ```
322
+ > **Note:**
323
+ In-memory storage resets when the process changes. Only suitable for development.
324
+
325
+ ## Options
326
+
327
+ ## Initialization
328
+
329
+ When you pass storage to the Mastra class, `init()` is called automatically to create the [core schema](https://mastra.ai/reference/storage/overview#core-schema):
330
+
331
+ ```typescript
332
+ import { Mastra } from "@mastra/core";
333
+ import { LibSQLStore } from "@mastra/libsql";
334
+
335
+ const storage = new LibSQLStore({
336
+ id: 'libsql-storage',
337
+ url: "file:./storage.db",
338
+ });
339
+
340
+ const mastra = new Mastra({
341
+ storage, // init() called automatically
342
+ });
343
+ ```
344
+
345
+ If using storage directly without Mastra, call `init()` explicitly:
346
+
347
+ ```typescript
348
+ import { LibSQLStore } from "@mastra/libsql";
349
+
350
+ const storage = new LibSQLStore({
351
+ id: 'libsql-storage',
352
+ url: "file:./storage.db",
353
+ });
354
+
355
+ await storage.init();
356
+
357
+ // Access domain-specific stores via getStore()
358
+ const memoryStore = await storage.getStore('memory');
359
+ const thread = await memoryStore?.getThreadById({ threadId: "..." });
360
+ ```
361
+
362
+ ---
363
+
364
+ ## Reference: MongoDB Storage
365
+
366
+ > Documentation for the MongoDB storage implementation in Mastra.
367
+
368
+ The MongoDB storage implementation provides a scalable storage solution using MongoDB databases with support for both document storage and vector operations.
369
+
370
+ ## Installation
371
+
372
+ ```bash
373
+ npm install @mastra/mongodb@latest
374
+ ```
375
+
376
+ ## Usage
377
+
378
+ Ensure you have a MongoDB Atlas Local (via Docker) or MongoDB Atlas Cloud instance with Atlas Search enabled. MongoDB 7.0+ is recommended.
379
+
380
+ ```typescript
381
+ import { MongoDBStore } from "@mastra/mongodb";
382
+
383
+ const storage = new MongoDBStore({
384
+ id: 'mongodb-storage',
385
+ uri: process.env.MONGODB_URI,
386
+ dbName: process.env.MONGODB_DATABASE,
387
+ });
388
+ ```
389
+
390
+ ## Parameters
391
+
392
+ > **Deprecation Notice**
393
+ The `url` parameter is deprecated but still supported for backward compatibility. Please use `uri` instead in all new code.
394
+
395
+ ## Constructor Examples
396
+
397
+ You can instantiate `MongoDBStore` in the following ways:
398
+
399
+ ```ts
400
+ import { MongoDBStore } from "@mastra/mongodb";
401
+
402
+ // Basic connection without custom options
403
+ const store1 = new MongoDBStore({
404
+ id: 'mongodb-storage-01',
405
+ uri: "mongodb+srv://user:password@cluster.mongodb.net",
406
+ dbName: "mastra_storage",
407
+ });
408
+
409
+ // Using connection string with options
410
+ const store2 = new MongoDBStore({
411
+ id: 'mongodb-storage-02',
412
+ uri: "mongodb+srv://user:password@cluster.mongodb.net",
413
+ dbName: "mastra_storage",
414
+ options: {
415
+ retryWrites: true,
416
+ maxPoolSize: 10,
417
+ serverSelectionTimeoutMS: 5000,
418
+ socketTimeoutMS: 45000,
419
+ },
420
+ });
421
+ ```
422
+
423
+ ## Additional Notes
424
+
425
+ ### Collection Management
426
+
427
+ The storage implementation handles collection creation and management automatically. It creates the following collections:
428
+
429
+ - `mastra_workflow_snapshot`: Stores workflow state and execution data
430
+ - `mastra_evals`: Stores evaluation results and metadata
431
+ - `mastra_threads`: Stores conversation threads
432
+ - `mastra_messages`: Stores individual messages
433
+ - `mastra_traces`: Stores telemetry and tracing data
434
+ - `mastra_scorers`: Stores scoring and evaluation data
435
+ - `mastra_resources`: Stores resource working memory data
436
+
437
+ ### Initialization
438
+
439
+ When you pass storage to the Mastra class, `init()` is called automatically before any storage operation:
440
+
441
+ ```typescript
442
+ import { Mastra } from "@mastra/core";
443
+ import { MongoDBStore } from "@mastra/mongodb";
444
+
445
+ const storage = new MongoDBStore({
446
+ id: 'mongodb-storage',
447
+ uri: process.env.MONGODB_URI,
448
+ dbName: process.env.MONGODB_DATABASE,
449
+ });
450
+
451
+ const mastra = new Mastra({
452
+ storage, // init() is called automatically
453
+ });
454
+ ```
455
+
456
+ If you're using storage directly without Mastra, you must call `init()` explicitly to create the collections:
457
+
458
+ ```typescript
459
+ import { MongoDBStore } from "@mastra/mongodb";
460
+
461
+ const storage = new MongoDBStore({
462
+ id: 'mongodb-storage',
463
+ uri: process.env.MONGODB_URI,
464
+ dbName: process.env.MONGODB_DATABASE,
465
+ });
466
+
467
+ // Required when using storage directly
468
+ await storage.init();
469
+
470
+ // Access domain-specific stores via getStore()
471
+ const memoryStore = await storage.getStore('memory');
472
+ const thread = await memoryStore?.getThreadById({ threadId: "..." });
473
+ ```
474
+
475
+ > **Note:**
476
+ If `init()` is not called, collections won't be created and storage operations will fail silently or throw errors.
477
+
478
+ ## Vector Search Capabilities
479
+
480
+ MongoDB storage includes built-in vector search capabilities for AI applications:
481
+
482
+ ### Vector Index Creation
483
+
484
+ ```typescript
485
+ import { MongoDBVector } from "@mastra/mongodb";
486
+
487
+ const vectorStore = new MongoDBVector({
488
+ id: 'mongodb-vector',
489
+ uri: process.env.MONGODB_URI,
490
+ dbName: process.env.MONGODB_DATABASE,
491
+ });
492
+
493
+ // Create a vector index for embeddings
494
+ await vectorStore.createIndex({
495
+ indexName: "document_embeddings",
496
+ dimension: 1536,
497
+ });
498
+ ```
499
+
500
+ ### Vector Operations
501
+
502
+ ```typescript
503
+ // Store vectors with metadata
504
+ await vectorStore.upsert({
505
+ indexName: "document_embeddings",
506
+ vectors: [
507
+ {
508
+ id: "doc-1",
509
+ values: [0.1, 0.2, 0.3, ...], // 1536-dimensional vector
510
+ metadata: {
511
+ title: "Document Title",
512
+ category: "technical",
513
+ source: "api-docs",
514
+ },
515
+ },
516
+ ],
517
+ });
518
+
519
+ // Similarity search
520
+ const results = await vectorStore.query({
521
+ indexName: "document_embeddings",
522
+ vector: queryEmbedding,
523
+ topK: 5,
524
+ filter: {
525
+ category: "technical",
526
+ },
527
+ });
528
+ ```
529
+
530
+ ## Usage Example
531
+
532
+ ### Adding memory to an agent
533
+
534
+ To add MongoDB memory to an agent use the `Memory` class and create a new `storage` key using `MongoDBStore`. The configuration supports both local and remote MongoDB instances.
535
+
536
+ ```typescript title="src/mastra/agents/example-mongodb-agent.ts"
537
+ import { Memory } from "@mastra/memory";
538
+ import { Agent } from "@mastra/core/agent";
539
+ import { MongoDBStore } from "@mastra/mongodb";
540
+
541
+ export const mongodbAgent = new Agent({
542
+ id: "mongodb-agent",
543
+ name: "mongodb-agent",
544
+ instructions:
545
+ "You are an AI agent with the ability to automatically recall memories from previous interactions.",
546
+ model: "openai/gpt-5.1",
547
+ memory: new Memory({
548
+ storage: new MongoDBStore({
549
+ uri: process.env.MONGODB_URI!,
550
+ dbName: process.env.MONGODB_DB_NAME!,
551
+ }),
552
+ options: {
553
+ generateTitle: true,
554
+ },
555
+ }),
556
+ });
557
+ ```
558
+
559
+ ### Using the agent
560
+
561
+ Use `memoryOptions` to scope recall for this request. Set `lastMessages: 5` to limit recency-based recall, and use `semanticRecall` to fetch the `topK: 3` most relevant messages, including `messageRange: 2` neighboring messages for context around each match.
562
+
563
+ ```typescript title="src/test-mongodb-agent.ts"
564
+ import "dotenv/config";
565
+
566
+ import { mastra } from "./mastra";
567
+
568
+ const threadId = "123";
569
+ const resourceId = "user-456";
570
+
571
+ const agent = mastra.getAgent("mongodbAgent");
572
+
573
+ const message = await agent.stream("My name is Mastra", {
574
+ memory: {
575
+ thread: threadId,
576
+ resource: resourceId,
577
+ },
578
+ });
579
+
580
+ await message.textStream.pipeTo(new WritableStream());
581
+
582
+ const stream = await agent.stream("What's my name?", {
583
+ memory: {
584
+ thread: threadId,
585
+ resource: resourceId,
586
+ },
587
+ memoryOptions: {
588
+ lastMessages: 5,
589
+ semanticRecall: {
590
+ topK: 3,
591
+ messageRange: 2,
592
+ },
593
+ },
594
+ });
595
+
596
+ for await (const chunk of stream.textStream) {
597
+ process.stdout.write(chunk);
598
+ }
599
+ ```
600
+
601
+ ---
602
+
603
+ ## Reference: PostgreSQL Storage
604
+
605
+ > Documentation for the PostgreSQL storage implementation in Mastra.
606
+
607
+ The PostgreSQL storage implementation provides a production-ready storage solution using PostgreSQL databases.
608
+
609
+ ## Installation
610
+
611
+ ```bash
612
+ npm install @mastra/pg@latest
613
+ ```
614
+
615
+ ## Usage
616
+
617
+ ```typescript
618
+ import { PostgresStore } from "@mastra/pg";
619
+
620
+ const storage = new PostgresStore({
621
+ id: 'pg-storage',
622
+ connectionString: process.env.DATABASE_URL,
623
+ });
624
+ ```
625
+
626
+ ## Parameters
627
+
628
+ ## Constructor Examples
629
+
630
+ You can instantiate `PostgresStore` in the following ways:
631
+
632
+ ```ts
633
+ import { PostgresStore } from "@mastra/pg";
634
+
635
+ // Using a connection string only
636
+ const store1 = new PostgresStore({
637
+ id: 'pg-storage-1',
638
+ connectionString: "postgresql://user:password@localhost:5432/mydb",
639
+ });
640
+
641
+ // Using a connection string with a custom schema name
642
+ const store2 = new PostgresStore({
643
+ id: 'pg-storage-2',
644
+ connectionString: "postgresql://user:password@localhost:5432/mydb",
645
+ schemaName: "custom_schema", // optional
646
+ });
647
+
648
+ // Using individual connection parameters
649
+ const store4 = new PostgresStore({
650
+ id: 'pg-storage-3',
651
+ host: "localhost",
652
+ port: 5432,
653
+ database: "mydb",
654
+ user: "user",
655
+ password: "password",
656
+ });
657
+
658
+ // Individual parameters with schemaName
659
+ const store5 = new PostgresStore({
660
+ id: 'pg-storage-4',
661
+ host: "localhost",
662
+ port: 5432,
663
+ database: "mydb",
664
+ user: "user",
665
+ password: "password",
666
+ schemaName: "custom_schema", // optional
667
+ });
668
+ ```
669
+
670
+ ## Additional Notes
671
+
672
+ ### Schema Management
673
+
674
+ The storage implementation handles schema creation and updates automatically. It creates the following tables:
675
+
676
+ - `mastra_workflow_snapshot`: Stores workflow state and execution data
677
+ - `mastra_evals`: Stores evaluation results and metadata
678
+ - `mastra_threads`: Stores conversation threads
679
+ - `mastra_messages`: Stores individual messages
680
+ - `mastra_traces`: Stores telemetry and tracing data
681
+ - `mastra_scorers`: Stores scoring and evaluation data
682
+ - `mastra_resources`: Stores resource working memory data
683
+
684
+ ### Initialization
685
+
686
+ When you pass storage to the Mastra class, `init()` is called automatically before any storage operation:
687
+
688
+ ```typescript
689
+ import { Mastra } from "@mastra/core";
690
+ import { PostgresStore } from "@mastra/pg";
691
+
692
+ const storage = new PostgresStore({
693
+ id: 'pg-storage',
694
+ connectionString: process.env.DATABASE_URL,
695
+ });
696
+
697
+ const mastra = new Mastra({
698
+ storage, // init() is called automatically
699
+ });
700
+ ```
701
+
702
+ If you're using storage directly without Mastra, you must call `init()` explicitly to create the tables:
703
+
704
+ ```typescript
705
+ import { PostgresStore } from "@mastra/pg";
706
+
707
+ const storage = new PostgresStore({
708
+ id: 'pg-storage',
709
+ connectionString: process.env.DATABASE_URL,
710
+ });
711
+
712
+ // Required when using storage directly
713
+ await storage.init();
714
+
715
+ // Access domain-specific stores via getStore()
716
+ const memoryStore = await storage.getStore('memory');
717
+ const thread = await memoryStore?.getThreadById({ threadId: "..." });
718
+ ```
719
+
720
+ > **Note:**
721
+ If `init()` is not called, tables won't be created and storage operations will fail silently or throw errors.
722
+
723
+ ### Direct Database and Pool Access
724
+
725
+ `PostgresStore` exposes both the underlying database object and the pg-promise instance as public fields:
726
+
727
+ ```typescript
728
+ store.db; // pg-promise database instance
729
+ store.pgp; // pg-promise main instance
730
+ ```
731
+
732
+ This enables direct queries and custom transaction management. When using these fields:
733
+
734
+ - You are responsible for proper connection and transaction handling.
735
+ - Closing the store (`store.close()`) will destroy the associated connection pool.
736
+ - Direct access bypasses any additional logic or validation provided by PostgresStore methods.
737
+
738
+ This approach is intended for advanced scenarios where low-level access is required.
739
+
740
+ ### Using with Next.js
741
+
742
+ When using `PostgresStore` in Next.js applications, [Hot Module Replacement (HMR)](https://nextjs.org/docs/architecture/fast-refresh) during development can cause multiple storage instances to be created, resulting in this warning:
743
+
744
+ ```
745
+ WARNING: Creating a duplicate database object for the same connection.
746
+ ```
747
+
748
+ To prevent this, store the `PostgresStore` instance on the global object so it persists across HMR reloads:
749
+
750
+ ```typescript title="src/mastra/storage.ts"
751
+ import { PostgresStore } from "@mastra/pg";
752
+ import { Memory } from "@mastra/memory";
753
+
754
+ // Extend the global type to include our instances
755
+ declare global {
756
+ var pgStore: PostgresStore | undefined;
757
+ var memory: Memory | undefined;
758
+ }
759
+
760
+ // Get or create the PostgresStore instance
761
+ function getPgStore(): PostgresStore {
762
+ if (!global.pgStore) {
763
+ if (!process.env.DATABASE_URL) {
764
+ throw new Error("DATABASE_URL is not defined in environment variables");
765
+ }
766
+ global.pgStore = new PostgresStore({
767
+ id: "pg-storage",
768
+ connectionString: process.env.DATABASE_URL,
769
+ ssl:
770
+ process.env.DATABASE_SSL === "true"
771
+ ? { rejectUnauthorized: false }
772
+ : false,
773
+ });
774
+ }
775
+ return global.pgStore;
776
+ }
777
+
778
+ // Get or create the Memory instance
779
+ function getMemory(): Memory {
780
+ if (!global.memory) {
781
+ global.memory = new Memory({
782
+ storage: getPgStore(),
783
+ });
784
+ }
785
+ return global.memory;
786
+ }
787
+
788
+ export const storage = getPgStore();
789
+ export const memory = getMemory();
790
+ ```
791
+
792
+ Then use the exported instances in your Mastra configuration:
793
+
794
+ ```typescript title="src/mastra/index.ts"
795
+ import { Mastra } from "@mastra/core/mastra";
796
+ import { storage } from "./storage";
797
+
798
+ export const mastra = new Mastra({
799
+ storage,
800
+ // ...other config
801
+ });
802
+ ```
803
+
804
+ This pattern ensures only one `PostgresStore` instance is created regardless of how many times the module is reloaded during development. The same pattern can be applied to other storage providers like `LibSQLStore`.
805
+
806
+ > **Note:**
807
+ This singleton pattern is only necessary during local development with HMR. In production builds, modules are only loaded once.
808
+
809
+ ## Usage Example
810
+
811
+ ### Adding memory to an agent
812
+
813
+ To add PostgreSQL memory to an agent use the `Memory` class and create a new `storage` key using `PostgresStore`. The `connectionString` can either be a remote location, or a local database connection.
814
+
815
+ ```typescript title="src/mastra/agents/example-pg-agent.ts"
816
+ import { Memory } from "@mastra/memory";
817
+ import { Agent } from "@mastra/core/agent";
818
+ import { PostgresStore } from "@mastra/pg";
819
+
820
+ export const pgAgent = new Agent({
821
+ id: "pg-agent",
822
+ name: "PG Agent",
823
+ instructions:
824
+ "You are an AI agent with the ability to automatically recall memories from previous interactions.",
825
+ model: "openai/gpt-5.1",
826
+ memory: new Memory({
827
+ storage: new PostgresStore({
828
+ id: 'pg-agent-storage',
829
+ connectionString: process.env.DATABASE_URL!,
830
+ }),
831
+ options: {
832
+ generateTitle: true, // Explicitly enable automatic title generation
833
+ },
834
+ }),
835
+ });
836
+ ```
837
+
838
+ ### Using the agent
839
+
840
+ Use `memoryOptions` to scope recall for this request. Set `lastMessages: 5` to limit recency-based recall, and use `semanticRecall` to fetch the `topK: 3` most relevant messages, including `messageRange: 2` neighboring messages for context around each match.
841
+
842
+ ```typescript title="src/test-pg-agent.ts"
843
+ import "dotenv/config";
844
+
845
+ import { mastra } from "./mastra";
846
+
847
+ const threadId = "123";
848
+ const resourceId = "user-456";
849
+
850
+ const agent = mastra.getAgent("pg-agent");
851
+
852
+ const message = await agent.stream("My name is Mastra", {
853
+ memory: {
854
+ thread: threadId,
855
+ resource: resourceId,
856
+ },
857
+ });
858
+
859
+ await message.textStream.pipeTo(new WritableStream());
860
+
861
+ const stream = await agent.stream("What's my name?", {
862
+ memory: {
863
+ thread: threadId,
864
+ resource: resourceId,
865
+ },
866
+ memoryOptions: {
867
+ lastMessages: 5,
868
+ semanticRecall: {
869
+ topK: 3,
870
+ messageRange: 2,
871
+ },
872
+ },
873
+ });
874
+
875
+ for await (const chunk of stream.textStream) {
876
+ process.stdout.write(chunk);
877
+ }
878
+ ```
879
+
880
+ ## Index Management
881
+
882
+ PostgreSQL storage provides index management to optimize query performance.
883
+
884
+ ### Default Indexes
885
+
886
+ PostgreSQL storage creates composite indexes during initialization for common query patterns:
887
+
888
+ - `mastra_threads_resourceid_createdat_idx`: (resourceId, createdAt DESC)
889
+ - `mastra_messages_thread_id_createdat_idx`: (thread_id, createdAt DESC)
890
+ - `mastra_ai_spans_traceid_startedat_idx`: (traceId, startedAt DESC)
891
+ - `mastra_ai_spans_parentspanid_startedat_idx`: (parentSpanId, startedAt DESC)
892
+ - `mastra_ai_spans_name_startedat_idx`: (name, startedAt DESC)
893
+ - `mastra_ai_spans_scope_startedat_idx`: (scope, startedAt DESC)
894
+ - `mastra_scores_trace_id_span_id_created_at_idx`: (traceId, spanId, createdAt DESC)
895
+
896
+ These indexes improve performance for filtered queries with sorting, including `dateRange` filters on message queries.
897
+
898
+ ### Configuring Indexes
899
+
900
+ You can control index creation via constructor options:
901
+
902
+ ```typescript
903
+ import { PostgresStore } from "@mastra/pg";
904
+
905
+ // Skip default indexes (manage indexes separately)
906
+ const store = new PostgresStore({
907
+ id: 'pg-storage',
908
+ connectionString: process.env.DATABASE_URL,
909
+ skipDefaultIndexes: true,
910
+ });
911
+
912
+ // Add custom indexes during initialization
913
+ const storeWithCustomIndexes = new PostgresStore({
914
+ id: 'pg-storage',
915
+ connectionString: process.env.DATABASE_URL,
916
+ indexes: [
917
+ {
918
+ name: "idx_threads_metadata_type",
919
+ table: "mastra_threads",
920
+ columns: ["metadata->>'type'"],
921
+ },
922
+ {
923
+ name: "idx_messages_status",
924
+ table: "mastra_messages",
925
+ columns: ["metadata->>'status'"],
926
+ },
927
+ ],
928
+ });
929
+ ```
930
+
931
+ For advanced index types, you can specify additional options:
932
+
933
+ - `unique: true` for unique constraints
934
+ - `where: 'condition'` for partial indexes
935
+ - `method: 'brin'` for time-series data
936
+ - `storage: { fillfactor: 90 }` for update-heavy tables
937
+ - `concurrent: true` for non-blocking creation (default)
938
+
939
+ ### Index Options
940
+
941
+ ### Schema-Specific Indexes
942
+
943
+ When using custom schemas, index names are prefixed with the schema name:
944
+
945
+ ```typescript
946
+ const storage = new PostgresStore({
947
+ id: 'pg-storage',
948
+ connectionString: process.env.DATABASE_URL,
949
+ schemaName: "custom_schema",
950
+ indexes: [
951
+ {
952
+ name: "idx_threads_status",
953
+ table: "mastra_threads",
954
+ columns: ["status"],
955
+ },
956
+ ],
957
+ });
958
+
959
+ // Creates index as: custom_schema_idx_threads_status
960
+ ```
961
+
962
+ ### Managing Indexes via SQL
963
+
964
+ For advanced index management (listing, dropping, analyzing), use direct SQL queries via the `db` accessor:
965
+
966
+ ```typescript
967
+ // List indexes for a table
968
+ const indexes = await storage.db.any(`
969
+ SELECT indexname, indexdef
970
+ FROM pg_indexes
971
+ WHERE tablename = 'mastra_messages'
972
+ `);
973
+
974
+ // Drop an index
975
+ await storage.db.none('DROP INDEX IF EXISTS idx_my_custom_index');
976
+
977
+ // Analyze index usage
978
+ const stats = await storage.db.one(`
979
+ SELECT idx_scan, idx_tup_read
980
+ FROM pg_stat_user_indexes
981
+ WHERE indexrelname = 'mastra_messages_thread_id_createdat_idx'
982
+ `);
983
+ ```
984
+
985
+ ### Index Types and Use Cases
986
+
987
+ PostgreSQL offers different index types optimized for specific scenarios:
988
+
989
+ | Index Type | Best For | Storage | Speed |
990
+ | ------------------- | --------------------------------------- | ---------- | -------------------------- |
991
+ | **btree** (default) | Range queries, sorting, general purpose | Moderate | Fast |
992
+ | **hash** | Equality comparisons only | Small | Very fast for `=` |
993
+ | **gin** | JSONB, arrays, full-text search | Large | Fast for contains |
994
+ | **gist** | Geometric data, full-text search | Moderate | Fast for nearest-neighbor |
995
+ | **spgist** | Non-balanced data, text patterns | Small | Fast for specific patterns |
996
+ | **brin** | Large tables with natural ordering | Very small | Fast for ranges |
997
+
998
+ ---
999
+
1000
+ ## Reference: Upstash Storage
1001
+
1002
+ > Documentation for the Upstash storage implementation in Mastra.
1003
+
1004
+ The Upstash storage implementation provides a serverless-friendly storage solution using Upstash's Redis-compatible key-value store.
1005
+
1006
+ > **Note:**
1007
+
1008
+ **Important:** When using Mastra with Upstash, the pay-as-you-go model can result in unexpectedly high costs due to the high volume of Redis commands generated during agent conversations. We strongly recommend using a **fixed pricing plan** for predictable costs. See [Upstash pricing](https://upstash.com/pricing/redis) for details and [GitHub issue #5850](https://github.com/mastra-ai/mastra/issues/5850) for context.
1009
+
1010
+ ## Installation
1011
+
1012
+ ```bash
1013
+ npm install @mastra/upstash@latest
1014
+ ```
1015
+
1016
+ ## Usage
1017
+
1018
+ ```typescript
1019
+ import { UpstashStore } from "@mastra/upstash";
1020
+
1021
+ const storage = new UpstashStore({
1022
+ id: 'upstash-storage',
1023
+ url: process.env.UPSTASH_URL,
1024
+ token: process.env.UPSTASH_TOKEN,
1025
+ });
1026
+ ```
1027
+
1028
+ ## Parameters
1029
+
1030
+ ## Additional Notes
1031
+
1032
+ ### Key Structure
1033
+
1034
+ The Upstash storage implementation uses a key-value structure:
1035
+
1036
+ - Thread keys: `{prefix}thread:{threadId}`
1037
+ - Message keys: `{prefix}message:{messageId}`
1038
+ - Metadata keys: `{prefix}metadata:{entityId}`
1039
+
1040
+ ### Serverless Benefits
1041
+
1042
+ Upstash storage is particularly well-suited for serverless deployments:
1043
+
1044
+ - No connection management needed
1045
+ - Pay-per-request pricing
1046
+ - Global replication options
1047
+ - Edge-compatible
1048
+
1049
+ ### Data Persistence
1050
+
1051
+ Upstash provides:
1052
+
1053
+ - Automatic data persistence
1054
+ - Point-in-time recovery
1055
+ - Cross-region replication options
1056
+
1057
+ ### Performance Considerations
1058
+
1059
+ For optimal performance:
1060
+
1061
+ - Use appropriate key prefixes to organize data
1062
+ - Monitor Redis memory usage
1063
+ - Consider data expiration policies if needed
1064
+
1065
+ ## Usage Example
1066
+
1067
+ ### Adding memory to an agent
1068
+
1069
+ To add Upstash memory to an agent use the `Memory` class and create a new `storage` key using `UpstashStore` and a new `vector` key using `UpstashVector`. The configuration can point to either a remote service or a local setup.
1070
+
1071
+ ```typescript title="src/mastra/agents/example-upstash-agent.ts"
1072
+ import { Memory } from "@mastra/memory";
1073
+ import { Agent } from "@mastra/core/agent";
1074
+ import { UpstashStore } from "@mastra/upstash";
1075
+
1076
+ export const upstashAgent = new Agent({
1077
+ id: "upstash-agent",
1078
+ name: "Upstash Agent",
1079
+ instructions:
1080
+ "You are an AI agent with the ability to automatically recall memories from previous interactions.",
1081
+ model: "openai/gpt-5.1",
1082
+ memory: new Memory({
1083
+ storage: new UpstashStore({
1084
+ id: 'upstash-agent-storage',
1085
+ url: process.env.UPSTASH_REDIS_REST_URL!,
1086
+ token: process.env.UPSTASH_REDIS_REST_TOKEN!,
1087
+ }),
1088
+ options: {
1089
+ generateTitle: true, // Explicitly enable automatic title generation
1090
+ },
1091
+ }),
1092
+ });
1093
+ ```
1094
+
1095
+ ### Using the agent
1096
+
1097
+ Use `memoryOptions` to scope recall for this request. Set `lastMessages: 5` to limit recency-based recall, and use `semanticRecall` to fetch the `topK: 3` most relevant messages, including `messageRange: 2` neighboring messages for context around each match.
1098
+
1099
+ ```typescript title="src/test-upstash-agent.ts"
1100
+ import "dotenv/config";
1101
+
1102
+ import { mastra } from "./mastra";
1103
+
1104
+ const threadId = "123";
1105
+ const resourceId = "user-456";
1106
+
1107
+ const agent = mastra.getAgent("upstashAgent");
1108
+
1109
+ const message = await agent.stream("My name is Mastra", {
1110
+ memory: {
1111
+ thread: threadId,
1112
+ resource: resourceId,
1113
+ },
1114
+ });
1115
+
1116
+ await message.textStream.pipeTo(new WritableStream());
1117
+
1118
+ const stream = await agent.stream("What's my name?", {
1119
+ memory: {
1120
+ thread: threadId,
1121
+ resource: resourceId,
1122
+ },
1123
+ memoryOptions: {
1124
+ lastMessages: 5,
1125
+ semanticRecall: {
1126
+ topK: 3,
1127
+ messageRange: 2,
1128
+ },
1129
+ },
1130
+ });
1131
+
1132
+ for await (const chunk of stream.textStream) {
1133
+ process.stdout.write(chunk);
1134
+ }
1135
+ ```