@mastra/memory 0.0.0-error-handler-fix-20251020202607 → 0.0.0-esbuild-bundle-worker-20260807182016

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 (169) hide show
  1. package/CHANGELOG.md +4656 -3
  2. package/LICENSE.md +15 -0
  3. package/README.md +26 -1
  4. package/dist/_types/@internal_ai-sdk-v4/dist/index.d.ts +7450 -0
  5. package/dist/docs/SKILL.md +62 -0
  6. package/dist/docs/assets/SOURCE_MAP.json +11 -0
  7. package/dist/docs/references/docs-agents-agent-approval.md +664 -0
  8. package/dist/docs/references/docs-agents-networks.md +184 -0
  9. package/dist/docs/references/docs-capabilities-subagents.md +454 -0
  10. package/dist/docs/references/docs-evals-evals-with-memory.md +146 -0
  11. package/dist/docs/references/docs-long-running-agents-background-tasks.md +382 -0
  12. package/dist/docs/references/docs-long-running-agents-goals.md +118 -0
  13. package/dist/docs/references/docs-memory-memory-processors.md +385 -0
  14. package/dist/docs/references/docs-memory-message-history.md +348 -0
  15. package/dist/docs/references/docs-memory-multi-user-threads.md +208 -0
  16. package/dist/docs/references/docs-memory-observational-memory.md +835 -0
  17. package/dist/docs/references/docs-memory-overview.md +266 -0
  18. package/dist/docs/references/docs-memory-semantic-recall.md +401 -0
  19. package/dist/docs/references/docs-memory-working-memory.md +431 -0
  20. package/dist/docs/references/docs-storage-overview.md +214 -0
  21. package/dist/docs/references/reference-core-getMemory.md +51 -0
  22. package/dist/docs/references/reference-core-listMemory.md +57 -0
  23. package/dist/docs/references/reference-file-based-agents-memory.md +58 -0
  24. package/dist/docs/references/reference-memory-clone-utilities.md +203 -0
  25. package/dist/docs/references/reference-memory-cloneThread.md +173 -0
  26. package/dist/docs/references/reference-memory-createThread.md +70 -0
  27. package/dist/docs/references/reference-memory-getThreadById.md +26 -0
  28. package/dist/docs/references/reference-memory-listThreads.md +147 -0
  29. package/dist/docs/references/reference-memory-memory-class.md +148 -0
  30. package/dist/docs/references/reference-memory-observational-memory.md +877 -0
  31. package/dist/docs/references/reference-memory-summarizeConversation.md +99 -0
  32. package/dist/docs/references/reference-memory-summarizeThread.md +93 -0
  33. package/dist/docs/references/reference-processors-token-limiter-processor.md +158 -0
  34. package/dist/docs/references/reference-storage-dsql.md +430 -0
  35. package/dist/docs/references/reference-storage-dynamodb.md +284 -0
  36. package/dist/docs/references/reference-storage-libsql.md +143 -0
  37. package/dist/docs/references/reference-storage-mongodb.md +267 -0
  38. package/dist/docs/references/reference-storage-postgresql.md +531 -0
  39. package/dist/docs/references/reference-storage-redis.md +268 -0
  40. package/dist/docs/references/reference-storage-upstash.md +162 -0
  41. package/dist/docs/references/reference-vectors-libsql.md +307 -0
  42. package/dist/docs/references/reference-vectors-mongodb.md +567 -0
  43. package/dist/docs/references/reference-vectors-pg.md +430 -0
  44. package/dist/docs/references/reference-vectors-upstash.md +296 -0
  45. package/dist/index.cjs +35 -893
  46. package/dist/index.d.ts +465 -62
  47. package/dist/index.d.ts.map +1 -1
  48. package/dist/index.js +2 -887
  49. package/dist/processors/index.cjs +32 -165
  50. package/dist/processors/index.d.ts +1 -2
  51. package/dist/processors/index.d.ts.map +1 -1
  52. package/dist/processors/index.js +2 -158
  53. package/dist/processors/observational-memory/activation-ttl.d.ts +4 -0
  54. package/dist/processors/observational-memory/activation-ttl.d.ts.map +1 -0
  55. package/dist/processors/observational-memory/anchor-ids.d.ts +4 -0
  56. package/dist/processors/observational-memory/anchor-ids.d.ts.map +1 -0
  57. package/dist/processors/observational-memory/buffering-coordinator.d.ts +61 -0
  58. package/dist/processors/observational-memory/buffering-coordinator.d.ts.map +1 -0
  59. package/dist/processors/observational-memory/built-in-extractors.d.ts +15 -0
  60. package/dist/processors/observational-memory/built-in-extractors.d.ts.map +1 -0
  61. package/dist/processors/observational-memory/constants.d.ts +74 -0
  62. package/dist/processors/observational-memory/constants.d.ts.map +1 -0
  63. package/dist/processors/observational-memory/date-utils.d.ts +41 -0
  64. package/dist/processors/observational-memory/date-utils.d.ts.map +1 -0
  65. package/dist/processors/observational-memory/debug.d.ts +3 -0
  66. package/dist/processors/observational-memory/debug.d.ts.map +1 -0
  67. package/dist/processors/observational-memory/extracted-values.d.ts +44 -0
  68. package/dist/processors/observational-memory/extracted-values.d.ts.map +1 -0
  69. package/dist/processors/observational-memory/extraction-runner.d.ts +22 -0
  70. package/dist/processors/observational-memory/extraction-runner.d.ts.map +1 -0
  71. package/dist/processors/observational-memory/extractor.d.ts +76 -0
  72. package/dist/processors/observational-memory/extractor.d.ts.map +1 -0
  73. package/dist/processors/observational-memory/index.d.ts +30 -0
  74. package/dist/processors/observational-memory/index.d.ts.map +1 -0
  75. package/dist/processors/observational-memory/internal-request-context.d.ts +17 -0
  76. package/dist/processors/observational-memory/internal-request-context.d.ts.map +1 -0
  77. package/dist/processors/observational-memory/markers.d.ts +118 -0
  78. package/dist/processors/observational-memory/markers.d.ts.map +1 -0
  79. package/dist/processors/observational-memory/message-utils.d.ts +83 -0
  80. package/dist/processors/observational-memory/message-utils.d.ts.map +1 -0
  81. package/dist/processors/observational-memory/model-by-input-tokens.d.ts +14 -0
  82. package/dist/processors/observational-memory/model-by-input-tokens.d.ts.map +1 -0
  83. package/dist/processors/observational-memory/model-context.d.ts +2 -0
  84. package/dist/processors/observational-memory/model-context.d.ts.map +1 -0
  85. package/dist/processors/observational-memory/observation-groups.d.ts +15 -0
  86. package/dist/processors/observational-memory/observation-groups.d.ts.map +1 -0
  87. package/dist/processors/observational-memory/observation-strategies/async-buffer.d.ts +39 -0
  88. package/dist/processors/observational-memory/observation-strategies/async-buffer.d.ts.map +1 -0
  89. package/dist/processors/observational-memory/observation-strategies/base.d.ts +122 -0
  90. package/dist/processors/observational-memory/observation-strategies/base.d.ts.map +1 -0
  91. package/dist/processors/observational-memory/observation-strategies/index.d.ts +7 -0
  92. package/dist/processors/observational-memory/observation-strategies/index.d.ts.map +1 -0
  93. package/dist/processors/observational-memory/observation-strategies/resource-scoped.d.ts +43 -0
  94. package/dist/processors/observational-memory/observation-strategies/resource-scoped.d.ts.map +1 -0
  95. package/dist/processors/observational-memory/observation-strategies/sync.d.ts +41 -0
  96. package/dist/processors/observational-memory/observation-strategies/sync.d.ts.map +1 -0
  97. package/dist/processors/observational-memory/observation-strategies/types.d.ts +103 -0
  98. package/dist/processors/observational-memory/observation-strategies/types.d.ts.map +1 -0
  99. package/dist/processors/observational-memory/observation-turn/index.d.ts +4 -0
  100. package/dist/processors/observational-memory/observation-turn/index.d.ts.map +1 -0
  101. package/dist/processors/observational-memory/observation-turn/load-memory-context.d.ts +9 -0
  102. package/dist/processors/observational-memory/observation-turn/load-memory-context.d.ts.map +1 -0
  103. package/dist/processors/observational-memory/observation-turn/step.d.ts +53 -0
  104. package/dist/processors/observational-memory/observation-turn/step.d.ts.map +1 -0
  105. package/dist/processors/observational-memory/observation-turn/turn.d.ts +139 -0
  106. package/dist/processors/observational-memory/observation-turn/turn.d.ts.map +1 -0
  107. package/dist/processors/observational-memory/observation-turn/types.d.ts +46 -0
  108. package/dist/processors/observational-memory/observation-turn/types.d.ts.map +1 -0
  109. package/dist/processors/observational-memory/observation-utils.d.ts +16 -0
  110. package/dist/processors/observational-memory/observation-utils.d.ts.map +1 -0
  111. package/dist/processors/observational-memory/observational-memory.d.ts +930 -0
  112. package/dist/processors/observational-memory/observational-memory.d.ts.map +1 -0
  113. package/dist/processors/observational-memory/observer-agent.d.ts +190 -0
  114. package/dist/processors/observational-memory/observer-agent.d.ts.map +1 -0
  115. package/dist/processors/observational-memory/observer-runner.d.ts +141 -0
  116. package/dist/processors/observational-memory/observer-runner.d.ts.map +1 -0
  117. package/dist/processors/observational-memory/operation-registry.d.ts +14 -0
  118. package/dist/processors/observational-memory/operation-registry.d.ts.map +1 -0
  119. package/dist/processors/observational-memory/processor.d.ts +70 -0
  120. package/dist/processors/observational-memory/processor.d.ts.map +1 -0
  121. package/dist/processors/observational-memory/reflector-agent.d.ts +62 -0
  122. package/dist/processors/observational-memory/reflector-agent.d.ts.map +1 -0
  123. package/dist/processors/observational-memory/reflector-runner.d.ts +133 -0
  124. package/dist/processors/observational-memory/reflector-runner.d.ts.map +1 -0
  125. package/dist/processors/observational-memory/repro-capture.d.ts +33 -0
  126. package/dist/processors/observational-memory/repro-capture.d.ts.map +1 -0
  127. package/dist/processors/observational-memory/retry.d.ts +63 -0
  128. package/dist/processors/observational-memory/retry.d.ts.map +1 -0
  129. package/dist/processors/observational-memory/string-utils.d.ts +13 -0
  130. package/dist/processors/observational-memory/string-utils.d.ts.map +1 -0
  131. package/dist/processors/observational-memory/summarize.d.ts +92 -0
  132. package/dist/processors/observational-memory/summarize.d.ts.map +1 -0
  133. package/dist/processors/observational-memory/temporal-markers.d.ts +4 -0
  134. package/dist/processors/observational-memory/temporal-markers.d.ts.map +1 -0
  135. package/dist/processors/observational-memory/temporary-memory.d.ts +8 -0
  136. package/dist/processors/observational-memory/temporary-memory.d.ts.map +1 -0
  137. package/dist/processors/observational-memory/thresholds.d.ts +52 -0
  138. package/dist/processors/observational-memory/thresholds.d.ts.map +1 -0
  139. package/dist/processors/observational-memory/token-counter.d.ts +57 -0
  140. package/dist/processors/observational-memory/token-counter.d.ts.map +1 -0
  141. package/dist/processors/observational-memory/tool-result-helpers.d.ts +12 -0
  142. package/dist/processors/observational-memory/tool-result-helpers.d.ts.map +1 -0
  143. package/dist/processors/observational-memory/tracing.d.ts +17 -0
  144. package/dist/processors/observational-memory/tracing.d.ts.map +1 -0
  145. package/dist/processors/observational-memory/types.d.ts +997 -0
  146. package/dist/processors/observational-memory/types.d.ts.map +1 -0
  147. package/dist/processors/observational-memory/working-memory-extractor.d.ts +5 -0
  148. package/dist/processors/observational-memory/working-memory-extractor.d.ts.map +1 -0
  149. package/dist/processors/working-memory-state/index.d.ts +2 -0
  150. package/dist/processors/working-memory-state/index.d.ts.map +1 -0
  151. package/dist/processors/working-memory-state/processor.d.ts +53 -0
  152. package/dist/processors/working-memory-state/processor.d.ts.map +1 -0
  153. package/dist/src-C1tlhGeW.js +28559 -0
  154. package/dist/src-C1tlhGeW.js.map +1 -0
  155. package/dist/src-DqoifKIy.cjs +28813 -0
  156. package/dist/src-DqoifKIy.cjs.map +1 -0
  157. package/dist/tools/om-tools.d.ts +172 -0
  158. package/dist/tools/om-tools.d.ts.map +1 -0
  159. package/dist/tools/working-memory.d.ts +33 -28
  160. package/dist/tools/working-memory.d.ts.map +1 -1
  161. package/package.json +36 -28
  162. package/dist/index.cjs.map +0 -1
  163. package/dist/index.js.map +0 -1
  164. package/dist/processors/index.cjs.map +0 -1
  165. package/dist/processors/index.js.map +0 -1
  166. package/dist/processors/token-limiter.d.ts +0 -32
  167. package/dist/processors/token-limiter.d.ts.map +0 -1
  168. package/dist/processors/tool-call-filter.d.ts +0 -20
  169. package/dist/processors/tool-call-filter.d.ts.map +0 -1
@@ -0,0 +1,531 @@
1
+ > Discover all available pages from the documentation index: https://mastra.ai/llms.txt
2
+
3
+ # PostgreSQL storage
4
+
5
+ The PostgreSQL storage implementation provides a production-ready storage solution using PostgreSQL databases.
6
+
7
+ ## Installation
8
+
9
+ **npm**:
10
+
11
+ ```bash
12
+ npm install @mastra/pg@latest
13
+ ```
14
+
15
+ **pnpm**:
16
+
17
+ ```bash
18
+ pnpm add @mastra/pg@latest
19
+ ```
20
+
21
+ **Yarn**:
22
+
23
+ ```bash
24
+ yarn add @mastra/pg@latest
25
+ ```
26
+
27
+ **Bun**:
28
+
29
+ ```bash
30
+ bun add @mastra/pg@latest
31
+ ```
32
+
33
+ ## Usage
34
+
35
+ ```typescript
36
+ import { PostgresStore } from '@mastra/pg'
37
+
38
+ const storage = new PostgresStore({
39
+ id: 'pg-storage',
40
+ connectionString: process.env.DATABASE_URL,
41
+ })
42
+ ```
43
+
44
+ ## Parameters
45
+
46
+ **id** (`string`): Unique identifier for this storage instance.
47
+
48
+ **connectionString** (`string`): PostgreSQL connection string (e.g., postgresql://user:pass\@host:5432/dbname). Required unless using pool or individual host-based parameters (host, port, database, user, password).
49
+
50
+ **host** (`string`): Database server hostname or IP address. Used with other host-based parameters as an alternative to connectionString.
51
+
52
+ **port** (`number`): Database server port number. Defaults to 5432 if not specified.
53
+
54
+ **database** (`string`): Name of the database to connect to.
55
+
56
+ **user** (`string`): Database user for authentication.
57
+
58
+ **password** (`string`): Password for the database user.
59
+
60
+ **pool** (`pg.Pool`): Pre-configured pg.Pool instance. Use this to reuse an existing connection pool. When provided, Mastra will not create its own pool and will not close it when store.close() is called.
61
+
62
+ **schemaName** (`string`): The name of the schema you want the storage to use. Defaults to 'public'.
63
+
64
+ **ssl** (`boolean | ConnectionOptions`): SSL configuration for the connection; set to true to use default SSL or provide a ConnectionOptions object for custom SSL settings.
65
+
66
+ **max** (`number`): Maximum number of connections in the pool. Defaults to 20.
67
+
68
+ **idleTimeoutMillis** (`number`): How long a connection can sit idle before being closed. Defaults to 30000 (30 seconds).
69
+
70
+ **disableInit** (`boolean`): When true, automatic table creation/migrations are disabled. Useful for CI/CD pipelines where migrations are run separately.
71
+
72
+ **skipDefaultIndexes** (`boolean`): When true, default indexes will not be created during initialization.
73
+
74
+ **indexes** (`CreateIndexOptions[]`): Custom indexes to create during initialization.
75
+
76
+ ## Constructor examples
77
+
78
+ You can instantiate `PostgresStore` in the following ways:
79
+
80
+ ```ts
81
+ import { PostgresStore } from '@mastra/pg'
82
+ import { Pool } from 'pg'
83
+
84
+ // Using a connection string
85
+ const store1 = new PostgresStore({
86
+ id: 'pg-storage-1',
87
+ connectionString: 'postgresql://user:password@localhost:5432/mydb',
88
+ })
89
+
90
+ // Using a connection string with pool options
91
+ const store2 = new PostgresStore({
92
+ id: 'pg-storage-2',
93
+ connectionString: 'postgresql://user:password@localhost:5432/mydb',
94
+ schemaName: 'custom_schema',
95
+ max: 30, // Max pool connections
96
+ idleTimeoutMillis: 60000, // Idle timeout
97
+ ssl: { rejectUnauthorized: false },
98
+ })
99
+
100
+ // Using individual connection parameters
101
+ const store3 = new PostgresStore({
102
+ id: 'pg-storage-3',
103
+ host: 'localhost',
104
+ port: 5432,
105
+ database: 'mydb',
106
+ user: 'user',
107
+ password: 'password',
108
+ })
109
+
110
+ // Using a pre-configured pg.Pool (recommended for pool reuse)
111
+ const existingPool = new Pool({
112
+ connectionString: 'postgresql://user:password@localhost:5432/mydb',
113
+ max: 20,
114
+ // ... your custom pool configuration
115
+ })
116
+
117
+ const store4 = new PostgresStore({
118
+ id: 'pg-storage-4',
119
+ pool: existingPool,
120
+ schemaName: 'custom_schema', // optional
121
+ })
122
+ ```
123
+
124
+ ## Additional notes
125
+
126
+ ### Schema Management
127
+
128
+ The storage implementation handles schema creation and updates automatically. It creates the following tables:
129
+
130
+ - `mastra_workflow_snapshot`: Stores workflow state and execution data
131
+ - `mastra_evals`: Stores evaluation results and metadata
132
+ - `mastra_threads`: Stores conversation threads
133
+ - `mastra_messages`: Stores individual messages
134
+ - `mastra_traces`: Stores telemetry and tracing data
135
+ - `mastra_scorers`: Stores scoring and evaluation data
136
+ - `mastra_resources`: Stores resource working memory data
137
+ - `mastra_notifications`: Stores notification inbox records and delivery metadata
138
+
139
+ `PostgresStore` exposes notification storage through `getStore('notifications')`.
140
+
141
+ ### Observability
142
+
143
+ PostgreSQL supports observability and can handle low trace volumes. Throughput capacity depends on deployment factors such as hardware, schema design, indexing, and retention policies, and should be validated for your specific environment. For high-volume production environments, consider:
144
+
145
+ - Using the `insert-only` [tracing strategy](https://mastra.ai/docs/observability/integrations/exporters/mastra-storage) to reduce database write operations
146
+ - Setting up table partitioning for efficient data retention
147
+ - Migrating observability to [ClickHouse via composite storage](https://mastra.ai/reference/storage/composite) if you need to scale further
148
+
149
+ ### Initialization
150
+
151
+ When you pass storage to the Mastra class, `init()` is called automatically before any storage operation:
152
+
153
+ ```typescript
154
+ import { Mastra } from '@mastra/core'
155
+ import { PostgresStore } from '@mastra/pg'
156
+
157
+ const storage = new PostgresStore({
158
+ id: 'pg-storage',
159
+ connectionString: process.env.DATABASE_URL,
160
+ })
161
+
162
+ const mastra = new Mastra({
163
+ storage, // init() is called automatically
164
+ })
165
+ ```
166
+
167
+ If you're using storage directly without Mastra, you must call `init()` explicitly to create the tables:
168
+
169
+ ```typescript
170
+ import { PostgresStore } from '@mastra/pg'
171
+
172
+ const storage = new PostgresStore({
173
+ id: 'pg-storage',
174
+ connectionString: process.env.DATABASE_URL,
175
+ })
176
+
177
+ // Required when using storage directly
178
+ await storage.init()
179
+
180
+ // Access domain-specific stores via getStore()
181
+ const memoryStore = await storage.getStore('memory')
182
+ const thread = await memoryStore?.getThreadById({ threadId: '...' })
183
+ ```
184
+
185
+ > **Warning:** If `init()` isn't called, tables won't be created and storage operations will fail silently or throw errors.
186
+
187
+ ### Using an Existing Pool
188
+
189
+ If you already have a `pg.Pool` in your application (e.g., shared with an ORM or for Row Level Security), you can pass it directly to `PostgresStore`:
190
+
191
+ ```typescript
192
+ import { Pool } from 'pg'
193
+ import { PostgresStore } from '@mastra/pg'
194
+
195
+ // Your existing pool (shared across your application)
196
+ const pool = new Pool({
197
+ connectionString: process.env.DATABASE_URL,
198
+ max: 20,
199
+ })
200
+
201
+ const storage = new PostgresStore({
202
+ id: 'shared-storage',
203
+ pool: pool,
204
+ })
205
+ ```
206
+
207
+ **Pool lifecycle behavior:**
208
+
209
+ - When you **provide a pool**: Mastra uses your pool but **doesn't** close it when `store.close()` is called. You manage the pool lifecycle.
210
+ - When Mastra **creates a pool**: Mastra owns the pool and will close it when `store.close()` is called.
211
+
212
+ ### Direct Database and Pool Access
213
+
214
+ `PostgresStore` exposes the underlying database client and pool for advanced use cases:
215
+
216
+ ```typescript
217
+ store.db // DbClient - query interface with helpers (any, one, tx, etc.)
218
+ store.pool // pg.Pool - the underlying connection pool
219
+ ```
220
+
221
+ **Using `store.db` for queries:**
222
+
223
+ ```typescript
224
+ // Execute queries with helper methods
225
+ const users = await store.db.any('SELECT * FROM users WHERE active = $1', [true])
226
+ const user = await store.db.one('SELECT * FROM users WHERE id = $1', [userId])
227
+ const maybeUser = await store.db.oneOrNone('SELECT * FROM users WHERE email = $1', [email])
228
+
229
+ // Use transactions
230
+ const result = await store.db.tx(async t => {
231
+ await t.none('INSERT INTO logs (message) VALUES ($1)', ['Started'])
232
+ const data = await t.any('SELECT * FROM items')
233
+ return data
234
+ })
235
+ ```
236
+
237
+ **Using `store.pool` directly:**
238
+
239
+ ```typescript
240
+ // Get a client for manual connection management
241
+ const client = await store.pool.connect()
242
+ try {
243
+ await client.query('SET LOCAL app.user_id = $1', [userId])
244
+ const result = await client.query('SELECT * FROM protected_table')
245
+ return result.rows
246
+ } finally {
247
+ client.release()
248
+ }
249
+ ```
250
+
251
+ When using these fields:
252
+
253
+ - You are responsible for proper connection and transaction handling.
254
+ - Closing the store (`store.close()`) will destroy the pool only if Mastra created it.
255
+ - Direct access bypasses any additional logic or validation provided by PostgresStore methods.
256
+
257
+ This approach is intended for advanced scenarios where low-level access is required.
258
+
259
+ ### Using with Next.js
260
+
261
+ 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:
262
+
263
+ ```text
264
+ WARNING: Creating a duplicate database object for the same connection.
265
+ ```
266
+
267
+ To prevent this, store the `PostgresStore` instance on the global object so it persists across HMR reloads:
268
+
269
+ ```typescript
270
+ import { PostgresStore } from '@mastra/pg'
271
+ import { Memory } from '@mastra/memory'
272
+
273
+ // Extend the global type to include our instances
274
+ declare global {
275
+ var pgStore: PostgresStore | undefined
276
+ var memory: Memory | undefined
277
+ }
278
+
279
+ // Get or create the PostgresStore instance
280
+ function getPgStore(): PostgresStore {
281
+ if (!global.pgStore) {
282
+ if (!process.env.DATABASE_URL) {
283
+ throw new Error('DATABASE_URL is not defined in environment variables')
284
+ }
285
+ global.pgStore = new PostgresStore({
286
+ id: 'pg-storage',
287
+ connectionString: process.env.DATABASE_URL,
288
+ ssl: process.env.DATABASE_SSL === 'true' ? { rejectUnauthorized: false } : false,
289
+ })
290
+ }
291
+ return global.pgStore
292
+ }
293
+
294
+ // Get or create the Memory instance
295
+ function getMemory(): Memory {
296
+ if (!global.memory) {
297
+ global.memory = new Memory({
298
+ storage: getPgStore(),
299
+ })
300
+ }
301
+ return global.memory
302
+ }
303
+
304
+ export const storage = getPgStore()
305
+ export const memory = getMemory()
306
+ ```
307
+
308
+ Then use the exported instances in your Mastra configuration:
309
+
310
+ ```typescript
311
+ import { Mastra } from '@mastra/core/mastra'
312
+ import { storage } from './storage'
313
+
314
+ export const mastra = new Mastra({
315
+ storage,
316
+ // ...other config
317
+ })
318
+ ```
319
+
320
+ The 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`.
321
+
322
+ > **Tip:** This singleton pattern is only necessary during local development with HMR. In production builds, modules are only loaded once.
323
+
324
+ ## Usage example
325
+
326
+ ### Adding memory to an agent
327
+
328
+ 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.
329
+
330
+ ```typescript
331
+ import { Memory } from '@mastra/memory'
332
+ import { Agent } from '@mastra/core/agent'
333
+ import { PostgresStore } from '@mastra/pg'
334
+
335
+ export const pgAgent = new Agent({
336
+ id: 'pg-agent',
337
+ name: 'PG Agent',
338
+ instructions:
339
+ 'You are an AI agent with the ability to automatically recall memories from previous interactions.',
340
+ model: 'openai/gpt-5.6-sol',
341
+ memory: new Memory({
342
+ storage: new PostgresStore({
343
+ id: 'pg-agent-storage',
344
+ connectionString: process.env.DATABASE_URL!,
345
+ }),
346
+ options: {
347
+ generateTitle: true, // Explicitly enable automatic title generation
348
+ },
349
+ }),
350
+ })
351
+ ```
352
+
353
+ ### Using the agent
354
+
355
+ 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.
356
+
357
+ ```typescript
358
+ import 'dotenv/config'
359
+
360
+ import { mastra } from './mastra'
361
+
362
+ const threadId = '123'
363
+ const resourceId = 'user-456'
364
+
365
+ const agent = mastra.getAgent('pg-agent')
366
+
367
+ const message = await agent.stream('My name is Mastra', {
368
+ memory: {
369
+ thread: threadId,
370
+ resource: resourceId,
371
+ },
372
+ })
373
+
374
+ await message.textStream.pipeTo(new WritableStream())
375
+
376
+ const stream = await agent.stream("What's my name?", {
377
+ memory: {
378
+ thread: threadId,
379
+ resource: resourceId,
380
+ },
381
+ memoryOptions: {
382
+ lastMessages: 5,
383
+ semanticRecall: {
384
+ topK: 3,
385
+ messageRange: 2,
386
+ },
387
+ },
388
+ })
389
+
390
+ for await (const chunk of stream.textStream) {
391
+ process.stdout.write(chunk)
392
+ }
393
+ ```
394
+
395
+ ## Index management
396
+
397
+ PostgreSQL storage provides index management to optimize query performance.
398
+
399
+ ### Default Indexes
400
+
401
+ PostgreSQL storage creates composite indexes during initialization for common query patterns:
402
+
403
+ - `mastra_threads_resourceid_createdat_idx`: (resourceId, createdAt DESC)
404
+ - `mastra_messages_thread_id_createdat_idx`: (thread\_id, createdAt DESC)
405
+ - `mastra_ai_spans_traceid_startedat_idx`: (traceId, startedAt DESC)
406
+ - `mastra_ai_spans_parentspanid_startedat_idx`: (parentSpanId, startedAt DESC)
407
+ - `mastra_ai_spans_name_startedat_idx`: (name, startedAt DESC)
408
+ - `mastra_ai_spans_scope_startedat_idx`: (scope, startedAt DESC)
409
+ - `mastra_scores_trace_id_span_id_created_at_idx`: (traceId, spanId, createdAt DESC)
410
+
411
+ These indexes improve performance for filtered queries with sorting, including `dateRange` filters on message queries.
412
+
413
+ ### Configuring Indexes
414
+
415
+ You can control index creation via constructor options:
416
+
417
+ ```typescript
418
+ import { PostgresStore } from '@mastra/pg'
419
+
420
+ // Skip default indexes (manage indexes separately)
421
+ const store = new PostgresStore({
422
+ id: 'pg-storage',
423
+ connectionString: process.env.DATABASE_URL,
424
+ skipDefaultIndexes: true,
425
+ })
426
+
427
+ // Add custom indexes during initialization
428
+ const storeWithCustomIndexes = new PostgresStore({
429
+ id: 'pg-storage',
430
+ connectionString: process.env.DATABASE_URL,
431
+ indexes: [
432
+ {
433
+ name: 'idx_threads_metadata_type',
434
+ table: 'mastra_threads',
435
+ columns: ["metadata->>'type'"],
436
+ },
437
+ {
438
+ name: 'idx_messages_status',
439
+ table: 'mastra_messages',
440
+ columns: ["metadata->>'status'"],
441
+ },
442
+ ],
443
+ })
444
+ ```
445
+
446
+ For advanced index types, you can specify additional options:
447
+
448
+ - `unique: true` for unique constraints
449
+ - `where: 'condition'` for partial indexes
450
+ - `method: 'brin'` for time-series data
451
+ - `storage: { fillfactor: 90 }` for update-heavy tables
452
+ - `concurrent: true` for non-blocking creation (default)
453
+
454
+ ### Index Options
455
+
456
+ **name** (`string`): Unique name for the index
457
+
458
+ **table** (`string`): Table name (e.g., 'mastra\_threads')
459
+
460
+ **columns** (`string[]`): Array of column names with optional sort order (e.g., \['id', 'createdAt DESC'])
461
+
462
+ **unique** (`boolean`): Creates a unique constraint index
463
+
464
+ **concurrent** (`boolean`): Creates index without locking table (default: true)
465
+
466
+ **where** (`string`): Partial index condition (PostgreSQL specific)
467
+
468
+ **method** (`'btree' | 'hash' | 'gin' | 'gist' | 'spgist' | 'brin'`): Index method (default: 'btree')
469
+
470
+ **opclass** (`string`): Operator class for GIN/GIST indexes
471
+
472
+ **storage** (`Record<string, any>`): Storage parameters (e.g., { fillfactor: 90 })
473
+
474
+ **tablespace** (`string`): Tablespace name for index placement
475
+
476
+ ### Schema-Specific Indexes
477
+
478
+ When using custom schemas, index names are prefixed with the schema name:
479
+
480
+ ```typescript
481
+ const storage = new PostgresStore({
482
+ id: 'pg-storage',
483
+ connectionString: process.env.DATABASE_URL,
484
+ schemaName: 'custom_schema',
485
+ indexes: [
486
+ {
487
+ name: 'idx_threads_status',
488
+ table: 'mastra_threads',
489
+ columns: ['status'],
490
+ },
491
+ ],
492
+ })
493
+
494
+ // Creates index as: custom_schema_idx_threads_status
495
+ ```
496
+
497
+ ### Managing Indexes via SQL
498
+
499
+ For advanced index management (listing, dropping, analyzing), use direct SQL queries via the `db` accessor:
500
+
501
+ ```typescript
502
+ // List indexes for a table
503
+ const indexes = await storage.db.any(`
504
+ SELECT indexname, indexdef
505
+ FROM pg_indexes
506
+ WHERE tablename = 'mastra_messages'
507
+ `)
508
+
509
+ // Drop an index
510
+ await storage.db.none('DROP INDEX IF EXISTS idx_my_custom_index')
511
+
512
+ // Analyze index usage
513
+ const stats = await storage.db.one(`
514
+ SELECT idx_scan, idx_tup_read
515
+ FROM pg_stat_user_indexes
516
+ WHERE indexrelname = 'mastra_messages_thread_id_createdat_idx'
517
+ `)
518
+ ```
519
+
520
+ ### Index Types and Use Cases
521
+
522
+ PostgreSQL offers different index types optimized for specific scenarios:
523
+
524
+ | Index Type | Best For | Storage | Speed |
525
+ | ------------------- | --------------------------------------- | ---------- | -------------------------- |
526
+ | **btree** (default) | Range queries, sorting, general purpose | Moderate | Fast |
527
+ | **hash** | Equality comparisons only | Small | Very fast for `=` |
528
+ | **gin** | JSONB, arrays, full-text search | Large | Fast for contains |
529
+ | **gist** | Geometric data, full-text search | Moderate | Fast for nearest-neighbor |
530
+ | **spgist** | Non-balanced data, text patterns | Small | Fast for specific patterns |
531
+ | **brin** | Large tables with natural ordering | Very small | Fast for ranges |