@mastra/upstash 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.
@@ -0,0 +1,34 @@
1
+ # @mastra/upstash Documentation
2
+
3
+ > Embedded documentation for coding agents
4
+
5
+ ## Quick Start
6
+
7
+ ```bash
8
+ # Read the skill overview
9
+ cat docs/SKILL.md
10
+
11
+ # Get the source map
12
+ cat docs/SOURCE_MAP.json
13
+
14
+ # Read topic documentation
15
+ cat docs/<topic>/01-overview.md
16
+ ```
17
+
18
+ ## Structure
19
+
20
+ ```
21
+ docs/
22
+ ├── SKILL.md # Entry point
23
+ ├── README.md # This file
24
+ ├── SOURCE_MAP.json # Export index
25
+ ├── memory/ (1 files)
26
+ ├── rag/ (2 files)
27
+ ├── storage/ (1 files)
28
+ ├── vectors/ (1 files)
29
+ ```
30
+
31
+ ## Version
32
+
33
+ Package: @mastra/upstash
34
+ Version: 1.0.0
@@ -0,0 +1,35 @@
1
+ ---
2
+ name: mastra-upstash-docs
3
+ description: Documentation for @mastra/upstash. Includes links to type definitions and readable implementation code in dist/.
4
+ ---
5
+
6
+ # @mastra/upstash Documentation
7
+
8
+ > **Version**: 1.0.0
9
+ > **Package**: @mastra/upstash
10
+
11
+ ## Quick Navigation
12
+
13
+ Use SOURCE_MAP.json to find any export:
14
+
15
+ ```bash
16
+ cat docs/SOURCE_MAP.json
17
+ ```
18
+
19
+ Each export maps to:
20
+ - **types**: `.d.ts` file with JSDoc and API signatures
21
+ - **implementation**: `.js` chunk file with readable source
22
+ - **docs**: Conceptual documentation in `docs/`
23
+
24
+ ## Top Exports
25
+
26
+
27
+
28
+ See SOURCE_MAP.json for the complete list.
29
+
30
+ ## Available Topics
31
+
32
+ - [Memory](memory/) - 1 file(s)
33
+ - [Rag](rag/) - 2 file(s)
34
+ - [Storage](storage/) - 1 file(s)
35
+ - [Vectors](vectors/) - 1 file(s)
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": "1.0.0",
3
+ "package": "@mastra/upstash",
4
+ "exports": {},
5
+ "modules": {}
6
+ }
@@ -0,0 +1,390 @@
1
+ > Learn how to configure working memory in Mastra to store persistent user data, preferences.
2
+
3
+ # Working Memory
4
+
5
+ While [message history](https://mastra.ai/docs/v1/memory/message-history) and [semantic recall](./semantic-recall) help agents remember conversations, working memory allows them to maintain persistent information about users across interactions.
6
+
7
+ Think of it as the agent's active thoughts or scratchpad – the key information they keep available about the user or task. It's similar to how a person would naturally remember someone's name, preferences, or important details during a conversation.
8
+
9
+ This is useful for maintaining ongoing state that's always relevant and should always be available to the agent.
10
+
11
+ Working memory can persist at two different scopes:
12
+
13
+ - **Resource-scoped** (default): Memory persists across all conversation threads for the same user
14
+ - **Thread-scoped**: Memory is isolated per conversation thread
15
+
16
+ **Important:** Switching between scopes means the agent won't see memory from the other scope - thread-scoped memory is completely separate from resource-scoped memory.
17
+
18
+ ## Quick Start
19
+
20
+ Here's a minimal example of setting up an agent with working memory:
21
+
22
+ ```typescript {11-15}
23
+ import { Agent } from "@mastra/core/agent";
24
+ import { Memory } from "@mastra/memory";
25
+
26
+ // Create agent with working memory enabled
27
+ const agent = new Agent({
28
+ id: "personal-assistant",
29
+ name: "PersonalAssistant",
30
+ instructions: "You are a helpful personal assistant.",
31
+ model: "openai/gpt-5.1",
32
+ memory: new Memory({
33
+ options: {
34
+ workingMemory: {
35
+ enabled: true,
36
+ },
37
+ },
38
+ }),
39
+ });
40
+ ```
41
+
42
+ ## How it Works
43
+
44
+ Working memory is a block of Markdown text that the agent is able to update over time to store continuously relevant information:
45
+
46
+ <YouTube id="UMy_JHLf1n8" />
47
+
48
+ ## Memory Persistence Scopes
49
+
50
+ Working memory can operate in two different scopes, allowing you to choose how memory persists across conversations:
51
+
52
+ ### Resource-Scoped Memory (Default)
53
+
54
+ By default, working memory persists across all conversation threads for the same user (resourceId), enabling persistent user memory:
55
+
56
+ ```typescript
57
+ const memory = new Memory({
58
+ storage,
59
+ options: {
60
+ workingMemory: {
61
+ enabled: true,
62
+ scope: "resource", // Memory persists across all user threads
63
+ template: `# User Profile
64
+ - **Name**:
65
+ - **Location**:
66
+ - **Interests**:
67
+ - **Preferences**:
68
+ - **Long-term Goals**:
69
+ `,
70
+ },
71
+ },
72
+ });
73
+ ```
74
+
75
+ **Use cases:**
76
+
77
+ - Personal assistants that remember user preferences
78
+ - Customer service bots that maintain customer context
79
+ - Educational applications that track student progress
80
+
81
+ ### Usage with Agents
82
+
83
+ When using resource-scoped memory, make sure to pass the `resource` parameter in the memory options:
84
+
85
+ ```typescript
86
+ // Resource-scoped memory requires resource
87
+ const response = await agent.generate("Hello!", {
88
+ memory: {
89
+ thread: "conversation-123",
90
+ resource: "user-alice-456", // Same user across different threads
91
+ },
92
+ });
93
+ ```
94
+
95
+ ### Thread-Scoped Memory
96
+
97
+ Thread-scoped memory isolates working memory to individual conversation threads. Each thread maintains its own isolated memory:
98
+
99
+ ```typescript
100
+ const memory = new Memory({
101
+ storage,
102
+ options: {
103
+ workingMemory: {
104
+ enabled: true,
105
+ scope: "thread", // Memory is isolated per thread
106
+ template: `# User Profile
107
+ - **Name**:
108
+ - **Interests**:
109
+ - **Current Goal**:
110
+ `,
111
+ },
112
+ },
113
+ });
114
+ ```
115
+
116
+ **Use cases:**
117
+
118
+ - Different conversations about separate topics
119
+ - Temporary or session-specific information
120
+ - Workflows where each thread needs working memory but threads are ephemeral and not related to each other
121
+
122
+ ## Storage Adapter Support
123
+
124
+ Resource-scoped working memory requires specific storage adapters that support the `mastra_resources` table:
125
+
126
+ ### Supported Storage Adapters
127
+
128
+ - **libSQL** (`@mastra/libsql`)
129
+ - **PostgreSQL** (`@mastra/pg`)
130
+ - **Upstash** (`@mastra/upstash`)
131
+ - **MongoDB** (`@mastra/mongodb`)
132
+
133
+ ## Custom Templates
134
+
135
+ Templates guide the agent on what information to track and update in working memory. While a default template is used if none is provided, you'll typically want to define a custom template tailored to your agent's specific use case to ensure it remembers the most relevant information.
136
+
137
+ Here's an example of a custom template. In this example the agent will store the users name, location, timezone, etc as soon as the user sends a message containing any of the info:
138
+
139
+ ```typescript {5-28}
140
+ const memory = new Memory({
141
+ options: {
142
+ workingMemory: {
143
+ enabled: true,
144
+ template: `
145
+ # User Profile
146
+
147
+ ## Personal Info
148
+
149
+ - Name:
150
+ - Location:
151
+ - Timezone:
152
+
153
+ ## Preferences
154
+
155
+ - Communication Style: [e.g., Formal, Casual]
156
+ - Project Goal:
157
+ - Key Deadlines:
158
+ - [Deadline 1]: [Date]
159
+ - [Deadline 2]: [Date]
160
+
161
+ ## Session State
162
+
163
+ - Last Task Discussed:
164
+ - Open Questions:
165
+ - [Question 1]
166
+ - [Question 2]
167
+ `,
168
+ },
169
+ },
170
+ });
171
+ ```
172
+
173
+ ## Designing Effective Templates
174
+
175
+ A well-structured template keeps the information easy for the agent to parse and update. Treat the
176
+ template as a short form that you want the assistant to keep up to date.
177
+
178
+ - **Short, focused labels.** Avoid paragraphs or very long headings. Keep labels brief (for example
179
+ `## Personal Info` or `- Name:`) so updates are easy to read and less likely to be truncated.
180
+ - **Use consistent casing.** Inconsistent capitalization (`Timezone:` vs `timezone:`) can cause messy
181
+ updates. Stick to Title Case or lower case for headings and bullet labels.
182
+ - **Keep placeholder text simple.** Use hints such as `[e.g., Formal]` or `[Date]` to help the LLM
183
+ fill in the correct spots.
184
+ - **Abbreviate very long values.** If you only need a short form, include guidance like
185
+ `- Name: [First name or nickname]` or `- Address (short):` rather than the full legal text.
186
+ - **Mention update rules in `instructions`.** You can instruct how and when to fill or clear parts of
187
+ the template directly in the agent's `instructions` field.
188
+
189
+ ### Alternative Template Styles
190
+
191
+ Use a shorter single block if you only need a few items:
192
+
193
+ ```typescript
194
+ const basicMemory = new Memory({
195
+ options: {
196
+ workingMemory: {
197
+ enabled: true,
198
+ template: `User Facts:\n- Name:\n- Favorite Color:\n- Current Topic:`,
199
+ },
200
+ },
201
+ });
202
+ ```
203
+
204
+ You can also store the key facts in a short paragraph format if you prefer a more narrative style:
205
+
206
+ ```typescript
207
+ const paragraphMemory = new Memory({
208
+ options: {
209
+ workingMemory: {
210
+ enabled: true,
211
+ template: `Important Details:\n\nKeep a short paragraph capturing the user's important facts (name, main goal, current task).`,
212
+ },
213
+ },
214
+ });
215
+ ```
216
+
217
+ ## Structured Working Memory
218
+
219
+ Working memory can also be defined using a structured schema instead of a Markdown template. This allows you to specify the exact fields and types that should be tracked, using a [Zod](https://zod.dev/) schema. When using a schema, the agent will see and update working memory as a JSON object matching your schema.
220
+
221
+ **Important:** You must specify either `template` or `schema`, but not both.
222
+
223
+ ### Example: Schema-Based Working Memory
224
+
225
+ ```typescript
226
+ import { z } from "zod";
227
+ import { Memory } from "@mastra/memory";
228
+
229
+ const userProfileSchema = z.object({
230
+ name: z.string().optional(),
231
+ location: z.string().optional(),
232
+ timezone: z.string().optional(),
233
+ preferences: z
234
+ .object({
235
+ communicationStyle: z.string().optional(),
236
+ projectGoal: z.string().optional(),
237
+ deadlines: z.array(z.string()).optional(),
238
+ })
239
+ .optional(),
240
+ });
241
+
242
+ const memory = new Memory({
243
+ options: {
244
+ workingMemory: {
245
+ enabled: true,
246
+ schema: userProfileSchema,
247
+ // template: ... (do not set)
248
+ },
249
+ },
250
+ });
251
+ ```
252
+
253
+ When a schema is provided, the agent receives the working memory as a JSON object. For example:
254
+
255
+ ```json
256
+ {
257
+ "name": "Sam",
258
+ "location": "Berlin",
259
+ "timezone": "CET",
260
+ "preferences": {
261
+ "communicationStyle": "Formal",
262
+ "projectGoal": "Launch MVP",
263
+ "deadlines": ["2025-07-01"]
264
+ }
265
+ }
266
+ ```
267
+
268
+ ### Merge Semantics for Schema-Based Memory
269
+
270
+ Schema-based working memory uses **merge semantics**, meaning the agent only needs to include fields it wants to add or update. Existing fields are preserved automatically.
271
+
272
+ - **Object fields are deep merged:** Only provided fields are updated; others remain unchanged
273
+ - **Set a field to `null` to delete it:** This explicitly removes the field from memory
274
+ - **Arrays are replaced entirely:** When an array field is provided, it replaces the existing array (arrays are not merged element-by-element)
275
+
276
+ ## Choosing Between Template and Schema
277
+
278
+ - Use a **template** (Markdown) if you want the agent to maintain memory as a free-form text block, such as a user profile or scratchpad. Templates use **replace semantics** — the agent must provide the complete memory content on each update.
279
+ - Use a **schema** if you need structured, type-safe data that can be validated and programmatically accessed as JSON. Schemas use **merge semantics** — the agent only provides fields to update, and existing fields are preserved.
280
+ - Only one mode can be active at a time: setting both `template` and `schema` is not supported.
281
+
282
+ ## Example: Multi-step Retention
283
+
284
+ Below is a simplified view of how the `User Profile` template updates across a short user
285
+ conversation:
286
+
287
+ ```nohighlight
288
+ # User Profile
289
+
290
+ ## Personal Info
291
+
292
+ - Name:
293
+ - Location:
294
+ - Timezone:
295
+
296
+ --- After user says "My name is **Sam** and I'm from **Berlin**" ---
297
+
298
+ # User Profile
299
+ - Name: Sam
300
+ - Location: Berlin
301
+ - Timezone:
302
+
303
+ --- After user adds "By the way I'm normally in **CET**" ---
304
+
305
+ # User Profile
306
+ - Name: Sam
307
+ - Location: Berlin
308
+ - Timezone: CET
309
+ ```
310
+
311
+ The agent can now refer to `Sam` or `Berlin` in later responses without requesting the information
312
+ again because it has been stored in working memory.
313
+
314
+ If your agent is not properly updating working memory when you expect it to, you can add system
315
+ instructions on _how_ and _when_ to use this template in your agent's `instructions` setting.
316
+
317
+ ## Setting Initial Working Memory
318
+
319
+ While agents typically update working memory through the `updateWorkingMemory` tool, you can also set initial working memory programmatically when creating or updating threads. This is useful for injecting user data (like their name, preferences, or other info) that you want available to the agent without passing it in every request.
320
+
321
+ ### Setting Working Memory via Thread Metadata
322
+
323
+ When creating a thread, you can provide initial working memory through the metadata's `workingMemory` key:
324
+
325
+ ```typescript title="src/app/medical-consultation.ts"
326
+ // Create a thread with initial working memory
327
+ const thread = await memory.createThread({
328
+ threadId: "thread-123",
329
+ resourceId: "user-456",
330
+ title: "Medical Consultation",
331
+ metadata: {
332
+ workingMemory: `# Patient Profile
333
+ - Name: John Doe
334
+ - Blood Type: O+
335
+ - Allergies: Penicillin
336
+ - Current Medications: None
337
+ - Medical History: Hypertension (controlled)
338
+ `,
339
+ },
340
+ });
341
+
342
+ // The agent will now have access to this information in all messages
343
+ await agent.generate("What's my blood type?", {
344
+ memory: {
345
+ thread: thread.id,
346
+ resource: "user-456",
347
+ },
348
+ });
349
+ // Response: "Your blood type is O+."
350
+ ```
351
+
352
+ ### Updating Working Memory Programmatically
353
+
354
+ You can also update an existing thread's working memory:
355
+
356
+ ```typescript title="src/app/medical-consultation.ts"
357
+ // Update thread metadata to add/modify working memory
358
+ await memory.updateThread({
359
+ id: "thread-123",
360
+ title: thread.title,
361
+ metadata: {
362
+ ...thread.metadata,
363
+ workingMemory: `# Patient Profile
364
+ - Name: John Doe
365
+ - Blood Type: O+
366
+ - Allergies: Penicillin, Ibuprofen // Updated
367
+ - Current Medications: Lisinopril 10mg daily // Added
368
+ - Medical History: Hypertension (controlled)
369
+ `,
370
+ },
371
+ });
372
+ ```
373
+
374
+ ### Direct Memory Update
375
+
376
+ Alternatively, use the `updateWorkingMemory` method directly:
377
+
378
+ ```typescript title="src/app/medical-consultation.ts"
379
+ await memory.updateWorkingMemory({
380
+ threadId: "thread-123",
381
+ resourceId: "user-456", // Required for resource-scoped memory
382
+ workingMemory: "Updated memory content...",
383
+ });
384
+ ```
385
+
386
+ ## Examples
387
+
388
+ - [Working memory with template](https://github.com/mastra-ai/mastra/tree/main/examples/memory-with-template)
389
+ - [Working memory with schema](https://github.com/mastra-ai/mastra/tree/main/examples/memory-with-schema)
390
+ - [Per-resource working memory](https://github.com/mastra-ai/mastra/tree/main/examples/memory-per-resource-example) - Complete example showing resource-scoped memory persistence