@mastra/memory 1.41.3 → 1.41.4-alpha.1

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.
@@ -3,7 +3,7 @@ name: mastra-memory
3
3
  description: Documentation for @mastra/memory. Use when working with @mastra/memory APIs, configuration, or implementation.
4
4
  metadata:
5
5
  package: "@mastra/memory"
6
- version: "1.41.3"
6
+ version: "1.41.4-alpha.1"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,243 +1,243 @@
1
1
  {
2
- "version": "1.41.3",
2
+ "version": "1.41.4-alpha.1",
3
3
  "package": "@mastra/memory",
4
4
  "exports": {
5
5
  "AUTO_MODEL_BY_PROVIDER": {
6
6
  "types": "dist/processors/observational-memory/auto-model.d.ts",
7
- "implementation": "dist/src-C6oJP8WI.js",
8
- "line": 32928
7
+ "implementation": "dist/src-SlK5VIXE.js",
8
+ "line": 32945
9
9
  },
10
10
  "Extractor": {
11
11
  "types": "dist/processors/observational-memory/extractor.d.ts",
12
- "implementation": "dist/src-C6oJP8WI.js",
12
+ "implementation": "dist/src-SlK5VIXE.js",
13
13
  "line": 24432
14
14
  },
15
15
  "ModelByInputTokens": {
16
16
  "types": "dist/processors/observational-memory/model-by-input-tokens.d.ts",
17
- "implementation": "dist/src-C6oJP8WI.js",
18
- "line": 32711
17
+ "implementation": "dist/src-SlK5VIXE.js",
18
+ "line": 32728
19
19
  },
20
20
  "OBSERVATIONAL_MEMORY_DEFAULTS": {
21
21
  "types": "dist/processors/observational-memory/constants.d.ts",
22
- "implementation": "dist/src-C6oJP8WI.js",
22
+ "implementation": "dist/src-SlK5VIXE.js",
23
23
  "line": 24168
24
24
  },
25
25
  "OBSERVATION_CONTEXT_INSTRUCTIONS": {
26
26
  "types": "dist/processors/observational-memory/constants.d.ts",
27
- "implementation": "dist/src-C6oJP8WI.js",
27
+ "implementation": "dist/src-SlK5VIXE.js",
28
28
  "line": 24229
29
29
  },
30
30
  "OBSERVATION_CONTEXT_PROMPT": {
31
31
  "types": "dist/processors/observational-memory/constants.d.ts",
32
- "implementation": "dist/src-C6oJP8WI.js",
32
+ "implementation": "dist/src-SlK5VIXE.js",
33
33
  "line": 24211
34
34
  },
35
35
  "OBSERVATION_CONTEXT_PROMPT_THREAD": {
36
36
  "types": "dist/processors/observational-memory/constants.d.ts",
37
- "implementation": "dist/src-C6oJP8WI.js",
37
+ "implementation": "dist/src-SlK5VIXE.js",
38
38
  "line": 24216
39
39
  },
40
40
  "OBSERVATION_CONTINUATION_HINT": {
41
41
  "types": "dist/processors/observational-memory/constants.d.ts",
42
- "implementation": "dist/src-C6oJP8WI.js",
42
+ "implementation": "dist/src-SlK5VIXE.js",
43
43
  "line": 24198
44
44
  },
45
45
  "OBSERVER_SYSTEM_PROMPT": {
46
46
  "types": "dist/processors/observational-memory/observer-agent.d.ts",
47
- "implementation": "dist/src-C6oJP8WI.js",
48
- "line": 26861
47
+ "implementation": "dist/src-SlK5VIXE.js",
48
+ "line": 26880
49
49
  },
50
50
  "ObservationalMemory": {
51
51
  "types": "dist/processors/observational-memory/observational-memory.d.ts",
52
- "implementation": "dist/src-C6oJP8WI.js",
53
- "line": 38045
52
+ "implementation": "dist/src-SlK5VIXE.js",
53
+ "line": 38063
54
54
  },
55
55
  "ObservationalMemoryProcessor": {
56
56
  "types": "dist/processors/observational-memory/processor.d.ts",
57
- "implementation": "dist/src-C6oJP8WI.js",
58
- "line": 40861
57
+ "implementation": "dist/src-SlK5VIXE.js",
58
+ "line": 40898
59
59
  },
60
60
  "TokenCounter": {
61
61
  "types": "dist/processors/observational-memory/token-counter.d.ts",
62
- "implementation": "dist/src-C6oJP8WI.js",
63
- "line": 29393
62
+ "implementation": "dist/src-SlK5VIXE.js",
63
+ "line": 29410
64
64
  },
65
65
  "WorkingMemoryExtractor": {
66
66
  "types": "dist/processors/observational-memory/working-memory-extractor.d.ts",
67
- "implementation": "dist/src-C6oJP8WI.js",
68
- "line": 30449
67
+ "implementation": "dist/src-SlK5VIXE.js",
68
+ "line": 30466
69
69
  },
70
70
  "buildObserverPrompt": {
71
71
  "types": "dist/processors/observational-memory/observer-agent.d.ts",
72
- "implementation": "dist/src-C6oJP8WI.js",
73
- "line": 27545
72
+ "implementation": "dist/src-SlK5VIXE.js",
73
+ "line": 27562
74
74
  },
75
75
  "buildObserverSystemPrompt": {
76
76
  "types": "dist/processors/observational-memory/observer-agent.d.ts",
77
- "implementation": "dist/src-C6oJP8WI.js",
78
- "line": 26755
77
+ "implementation": "dist/src-SlK5VIXE.js",
78
+ "line": 26774
79
79
  },
80
80
  "combineObservationGroupRanges": {
81
81
  "types": "dist/processors/observational-memory/observation-groups.d.ts",
82
- "implementation": "dist/src-C6oJP8WI.js",
83
- "line": 31031
82
+ "implementation": "dist/src-SlK5VIXE.js",
83
+ "line": 31048
84
84
  },
85
85
  "deriveObservationGroupProvenance": {
86
86
  "types": "dist/processors/observational-memory/observation-groups.d.ts",
87
- "implementation": "dist/src-C6oJP8WI.js",
88
- "line": 31075
87
+ "implementation": "dist/src-SlK5VIXE.js",
88
+ "line": 31092
89
89
  },
90
90
  "extractCurrentTask": {
91
91
  "types": "dist/processors/observational-memory/observer-agent.d.ts",
92
- "implementation": "dist/src-C6oJP8WI.js",
93
- "line": 27858
92
+ "implementation": "dist/src-SlK5VIXE.js",
93
+ "line": 27875
94
94
  },
95
95
  "formatMessagesForObserver": {
96
96
  "types": "dist/processors/observational-memory/observer-agent.d.ts",
97
- "implementation": "dist/src-C6oJP8WI.js",
98
- "line": 27296
97
+ "implementation": "dist/src-SlK5VIXE.js",
98
+ "line": 27313
99
99
  },
100
100
  "getObservationContextPrompt": {
101
101
  "types": "dist/processors/observational-memory/constants.d.ts",
102
- "implementation": "dist/src-C6oJP8WI.js",
102
+ "implementation": "dist/src-SlK5VIXE.js",
103
103
  "line": 24222
104
104
  },
105
105
  "getObservationsAsOf": {
106
106
  "types": "dist/processors/observational-memory/observation-utils.d.ts",
107
- "implementation": "dist/src-C6oJP8WI.js",
108
- "line": 41206
107
+ "implementation": "dist/src-SlK5VIXE.js",
108
+ "line": 41244
109
109
  },
110
110
  "hasCurrentTaskSection": {
111
111
  "types": "dist/processors/observational-memory/observer-agent.d.ts",
112
- "implementation": "dist/src-C6oJP8WI.js",
113
- "line": 27846
112
+ "implementation": "dist/src-SlK5VIXE.js",
113
+ "line": 27863
114
114
  },
115
115
  "injectAnchorIds": {
116
116
  "types": "dist/processors/observational-memory/anchor-ids.d.ts",
117
- "implementation": "dist/src-C6oJP8WI.js",
117
+ "implementation": "dist/src-SlK5VIXE.js",
118
118
  "line": 25432
119
119
  },
120
120
  "optimizeObservationsForContext": {
121
121
  "types": "dist/processors/observational-memory/observer-agent.d.ts",
122
- "implementation": "dist/src-C6oJP8WI.js",
123
- "line": 27879
122
+ "implementation": "dist/src-SlK5VIXE.js",
123
+ "line": 27896
124
124
  },
125
125
  "parseAnchorId": {
126
126
  "types": "dist/processors/observational-memory/anchor-ids.d.ts",
127
- "implementation": "dist/src-C6oJP8WI.js",
127
+ "implementation": "dist/src-SlK5VIXE.js",
128
128
  "line": 25416
129
129
  },
130
130
  "parseObservationGroups": {
131
131
  "types": "dist/processors/observational-memory/observation-groups.d.ts",
132
- "implementation": "dist/src-C6oJP8WI.js",
133
- "line": 30986
132
+ "implementation": "dist/src-SlK5VIXE.js",
133
+ "line": 31003
134
134
  },
135
135
  "parseObserverOutput": {
136
136
  "types": "dist/processors/observational-memory/observer-agent.d.ts",
137
- "implementation": "dist/src-C6oJP8WI.js",
138
- "line": 27556
137
+ "implementation": "dist/src-SlK5VIXE.js",
138
+ "line": 27573
139
139
  },
140
140
  "reconcileObservationGroupsFromReflection": {
141
141
  "types": "dist/processors/observational-memory/observation-groups.d.ts",
142
- "implementation": "dist/src-C6oJP8WI.js",
143
- "line": 31094
142
+ "implementation": "dist/src-SlK5VIXE.js",
143
+ "line": 31111
144
144
  },
145
145
  "renderObservationGroupsForReflection": {
146
146
  "types": "dist/processors/observational-memory/observation-groups.d.ts",
147
- "implementation": "dist/src-C6oJP8WI.js",
148
- "line": 31060
147
+ "implementation": "dist/src-SlK5VIXE.js",
148
+ "line": 31077
149
149
  },
150
150
  "resolveAutoModelId": {
151
151
  "types": "dist/processors/observational-memory/auto-model.d.ts",
152
- "implementation": "dist/src-C6oJP8WI.js",
153
- "line": 32948
152
+ "implementation": "dist/src-SlK5VIXE.js",
153
+ "line": 32965
154
154
  },
155
155
  "stripEphemeralAnchorIds": {
156
156
  "types": "dist/processors/observational-memory/anchor-ids.d.ts",
157
- "implementation": "dist/src-C6oJP8WI.js",
157
+ "implementation": "dist/src-SlK5VIXE.js",
158
158
  "line": 25455
159
159
  },
160
160
  "stripObservationGroups": {
161
161
  "types": "dist/processors/observational-memory/observation-groups.d.ts",
162
- "implementation": "dist/src-C6oJP8WI.js",
163
- "line": 31003
162
+ "implementation": "dist/src-SlK5VIXE.js",
163
+ "line": 31020
164
164
  },
165
165
  "summarizeConversation": {
166
166
  "types": "dist/processors/observational-memory/summarize.d.ts",
167
- "implementation": "dist/src-C6oJP8WI.js",
168
- "line": 30061
167
+ "implementation": "dist/src-SlK5VIXE.js",
168
+ "line": 30078
169
169
  },
170
170
  "wrapInObservationGroup": {
171
171
  "types": "dist/processors/observational-memory/observation-groups.d.ts",
172
- "implementation": "dist/src-C6oJP8WI.js",
173
- "line": 30957
172
+ "implementation": "dist/src-SlK5VIXE.js",
173
+ "line": 30974
174
174
  },
175
175
  "KnowledgeSemanticIndexCoordinator": {
176
176
  "types": "dist/removed-subconscious.d.ts",
177
- "implementation": "dist/src-C6oJP8WI.js",
178
- "line": 30555
177
+ "implementation": "dist/src-SlK5VIXE.js",
178
+ "line": 30572
179
179
  },
180
180
  "Memory": {
181
181
  "types": "dist/index.d.ts",
182
- "implementation": "dist/src-C6oJP8WI.js",
183
- "line": 41437
182
+ "implementation": "dist/src-SlK5VIXE.js",
183
+ "line": 41496
184
184
  },
185
185
  "SUMMARIZE_THREAD_DEFAULTS": {
186
186
  "types": "dist/processors/observational-memory/summarize.d.ts",
187
- "implementation": "dist/src-C6oJP8WI.js",
188
- "line": 30017
187
+ "implementation": "dist/src-SlK5VIXE.js",
188
+ "line": 30034
189
189
  },
190
190
  "StaleKnowledgeSemanticIndexError": {
191
191
  "types": "dist/removed-subconscious.d.ts",
192
- "implementation": "dist/src-C6oJP8WI.js",
193
- "line": 30561
192
+ "implementation": "dist/src-SlK5VIXE.js",
193
+ "line": 30578
194
194
  },
195
195
  "Subconscious": {
196
196
  "types": "dist/removed-subconscious.d.ts",
197
- "implementation": "dist/src-C6oJP8WI.js",
198
- "line": 30549
197
+ "implementation": "dist/src-SlK5VIXE.js",
198
+ "line": 30566
199
199
  },
200
200
  "WORKING_MEMORY_STATE_ID": {
201
201
  "types": "dist/processors/working-memory-state/processor.d.ts",
202
- "implementation": "dist/src-C6oJP8WI.js",
203
- "line": 32757
202
+ "implementation": "dist/src-SlK5VIXE.js",
203
+ "line": 32774
204
204
  },
205
205
  "WORKING_MEMORY_STATE_PROCESSOR_ID": {
206
206
  "types": "dist/processors/working-memory-state/processor.d.ts",
207
- "implementation": "dist/src-C6oJP8WI.js",
208
- "line": 32758
207
+ "implementation": "dist/src-SlK5VIXE.js",
208
+ "line": 32775
209
209
  },
210
210
  "WorkingMemoryStateProcessor": {
211
211
  "types": "dist/processors/working-memory-state/processor.d.ts",
212
- "implementation": "dist/src-C6oJP8WI.js",
213
- "line": 32759
212
+ "implementation": "dist/src-SlK5VIXE.js",
213
+ "line": 32776
214
214
  },
215
215
  "deepMergeWorkingMemory": {
216
216
  "types": "dist/tools/working-memory.d.ts",
217
- "implementation": "dist/src-C6oJP8WI.js",
218
- "line": 30140
217
+ "implementation": "dist/src-SlK5VIXE.js",
218
+ "line": 30157
219
219
  },
220
220
  "extractWorkingMemoryContent": {
221
221
  "types": "dist/index.d.ts",
222
- "implementation": "dist/src-C6oJP8WI.js",
223
- "line": 41271
222
+ "implementation": "dist/src-SlK5VIXE.js",
223
+ "line": 41309
224
224
  },
225
225
  "extractWorkingMemoryTags": {
226
226
  "types": "dist/index.d.ts",
227
- "implementation": "dist/src-C6oJP8WI.js",
228
- "line": 41239
227
+ "implementation": "dist/src-SlK5VIXE.js",
228
+ "line": 41277
229
229
  },
230
230
  "removeWorkingMemoryTags": {
231
231
  "types": "dist/index.d.ts",
232
- "implementation": "dist/src-C6oJP8WI.js",
233
- "line": 41252
232
+ "implementation": "dist/src-SlK5VIXE.js",
233
+ "line": 41290
234
234
  }
235
235
  },
236
236
  "modules": {
237
237
  "processors": {
238
238
  "index": "dist/processors/index.js",
239
239
  "chunks": [
240
- "src-C6oJP8WI.js"
240
+ "src-SlK5VIXE.js"
241
241
  ]
242
242
  }
243
243
  }
@@ -110,7 +110,7 @@ const stream = await routingAgent.network('Perform some sensitive action', {
110
110
  for await (const chunk of stream) {
111
111
  if (chunk.type === 'agent-execution-approval' || chunk.type === 'tool-execution-approval') {
112
112
  // Approve
113
- const approvedStream = await routingAgent.approveNetworkToolCall(chunk.payload.toolCallId, {
113
+ const approvedStream = await routingAgent.approveNetworkToolCall({
114
114
  runId: stream.runId,
115
115
  memory: { thread: 'user-123', resource: 'my-app' },
116
116
  })
@@ -98,6 +98,25 @@ export const researcher = new Agent({
98
98
 
99
99
  Set `tools: 'all'` to opt in every tool the agent has.
100
100
 
101
+ ### Agent-wide defaults
102
+
103
+ Agent-wide `defaultDisposition` and `modelOverrides` sit next to `tools` and apply to every tool the agent has opted in, so you don't have to repeat them per tool:
104
+
105
+ ```typescript
106
+ export const researcher = new Agent({
107
+ // ...
108
+ backgroundTasks: {
109
+ tools: 'all',
110
+ defaultDisposition: 'foreground',
111
+ modelOverrides: false,
112
+ },
113
+ })
114
+ ```
115
+
116
+ Both act as defaults. For each tool the agent has opted in, `defaultDisposition` resolves as the tool entry's own value, then the agent-wide value, then the tool's own `background` config, then `deferred`. `modelOverrides` resolves the same way but defaults to `true`. `enabled` is never inherited, so agent-wide fields can't opt a tool in on their own.
117
+
118
+ Agent-wide values apply to named entries too, so a plain `tools: { research: true }` inherits them. An entry can still opt out per tool with its own `defaultDisposition` or `modelOverrides`. `defaultDisposition` accepts `'foreground'` or `'deferred'`, so `awaited` remains a per-call `_background` choice.
119
+
101
120
  ### LLM per-call override
102
121
 
103
122
  When a tool is registered on an agent that has background tasks enabled, the model can include a `_background` field in the tool arguments to override the resolved configuration for that specific call. The model only includes what it wants to override, all fields in `_background` are optional. The override is stripped from the arguments before the tool runs.
@@ -119,6 +138,25 @@ For compatibility, `_background.enabled: true` selects `deferred`, and `_backgro
119
138
 
120
139
  The `_background` override only _modifies_ tools the developer has already opted in at the tool or agent layer. If a tool hasn't been opted in, a model-selected background disposition is ignored and the tool runs in the foreground. This keeps deterministic, foreground-only tools (calculators, lookups, schema validators) from being silently dispatched as tasks.
121
140
 
141
+ ### Disable the per-call override
142
+
143
+ The `_background` object adds five optional parameters to each eligible tool's input schema: the object itself plus `enabled`, `disposition`, `timeoutMs`, and `maxRetries`. Some providers cap optional parameters per request. Anthropic rejects strict tool schemas with more than 24 optional parameters in total, so five strict background tools exceed the limit before counting their own optional fields.
144
+
145
+ Set `modelOverrides: false` when a tool should always use its configured disposition. Mastra then leaves `_background` out of the tool's schema and the system prompt, and ignores any `_background` value the model sends:
146
+
147
+ ```typescript
148
+ const researchTool = createTool({
149
+ id: 'research',
150
+ description: 'Research a topic in depth',
151
+ strict: true,
152
+ inputSchema: z.object({ topic: z.string() }),
153
+ background: { enabled: true, modelOverrides: false },
154
+ execute: async ({ topic }) => runResearch(topic),
155
+ })
156
+ ```
157
+
158
+ You can also set `modelOverrides: false` on an agent's per-tool entry, for example `backgroundTasks: { tools: { research: { enabled: true, modelOverrides: false } } }`. The agent entry takes precedence over the tool definition. Tools with `modelOverrides: false` and `defaultDisposition: 'foreground'` always run in the foreground.
159
+
122
160
  ### Resolution order
123
161
 
124
162
  When a tool call is dispatched, agent-level and tool-level settings determine eligibility and fallback values. For an eligible tool, the LLM `_background` fields override the corresponding values for that call. Manager defaults fill timeout and retry values that remain unset. An `_background` field can't enable a tool that's not eligible.
@@ -496,7 +534,7 @@ Every Mastra process with background tasks enabled runs its own manager. You can
496
534
  ### Deployment requirements
497
535
 
498
536
  - Every manager must use the same storage backend, and its `updateTask` must apply the write conditions atomically. Mastra's storage adapters do. In-memory storage is only shared within one process.
499
- - `leaseExpiresAt` is a timestamp written with the owner's clock and compared against the clock of the manager that reads it. Keep server clocks synchronized, for example with Network Time Protocol (NTP), to well under `leaseDurationMs`. If a reader's clock runs ahead by more than the lease, it can recover a task whose owner is still alive. If it runs behind, recovery is delayed. The startup scan recovers a task as soon as its lease has expired by the reader's clock. Follow-up scans wait about one second past the expiry to absorb small differences.
537
+ - `leaseExpiresAt` is a timestamp written with the owner's clock and compared against the clock of the manager that reads it. Keep server clocks synchronized, for example with Network Time Protocol (NTP), to well under `leaseDurationMs`. If a reader's clock runs ahead by more than the lease, it can recover a task whose owner is still alive. If it runs behind, recovery is delayed. The startup scan and the periodic check recover a task as soon as its lease has expired by the reader's clock. Follow-up scans wait about one second past the expiry to absorb small differences.
500
538
  - A longer [`leaseDurationMs`](https://mastra.ai/reference/configuration) delays recovery after a crash. A shorter one adds storage writes and makes it more likely that a stalled owner loses its lease while still running. The default is 30 seconds and the minimum is 3000 ms.
501
539
 
502
540
  ### Lease guarantees and repeated tool calls
@@ -519,17 +557,17 @@ Before a manager runs a task, it claims the task with a conditional write. The w
519
557
 
520
558
  While the task runs, the owner renews the lease every `leaseDurationMs / 3`, with a minimum of one second. Each renewal is conditional on the task still being `running` under the same owner. The task's final writes, such as `completed`, `failed`, `timed_out`, or `suspended`, carry the same condition, so a manager that lost the task can't overwrite the result of the manager that replaced it.
521
559
 
522
- The owner stops renewing when the task completes, fails, or suspends. On shutdown, the manager releases the leases it still holds, so other managers can recover those tasks without waiting for the lease to expire. A lease that isn't released, for example because the process crashed, expires on its own.
560
+ The owner stops renewing when the task completes, fails, or suspends. On shutdown, the manager releases the leases it still holds, so other managers can recover those tasks without waiting for the lease to expire. A running task with `maxRetries: 0` can't run again, so shutdown fails it with `Worker process terminated before task completed`, the same ending as a crash, rather than cancelling it. A lease that isn't released, for example because the process crashed, expires on its own.
523
561
 
524
562
  ### Recover a task from a dead owner
525
563
 
526
564
  A manager treats a `running` task as abandoned only after its lease expires.
527
565
 
528
- When `recoverStaleTasksOnStart` is `true`, the default, each manager that runs tasks scans for abandoned tasks on startup. If the scan finds a lease that hasn't expired yet, the manager scans again shortly after that lease expires, and repeats until no live lease is left. A task that a manager starts after that and then abandons waits for the next startup scan. For each task the scan recovers:
566
+ When `recoverStaleTasksOnStart` is `true`, the default, each manager that runs tasks scans for abandoned tasks on startup. If the scan finds a lease that hasn't expired yet, the manager scans again shortly after that lease expires, and repeats until no live lease is left. After startup, the manager also checks for running tasks with an expired lease every `leaseDurationMs`, so a task whose worker dies later is recovered without a restart. Each check reads up to `globalConcurrency` running tasks (at least 100, at most 1,000), which normally covers all of them, so the task is recovered within about one `leaseDurationMs` after its lease expires. When more tasks are running than that, for example because other servers use a higher `globalConcurrency`, each further page of running tasks adds one `leaseDurationMs`. For each task the scan recovers:
529
567
 
530
568
  - If the task's worker shut down gracefully, it returns to `pending` and is dispatched again without using a retry.
531
569
  - If the worker died and the task's `retryCount` is below `maxRetries`, it uses a retry, returns to `pending`, and is dispatched again.
532
- - Otherwise, it fails with `Worker process terminated before task completed`.
570
+ - Otherwise, it fails with `Worker process terminated before task completed`. The failure fires `task.failed` and `onTaskFailed` like any other failure.
533
571
 
534
572
  Only a crash counts against `maxRetries`, so a task that keeps taking its worker down stops after its retries are used, while a deploy doesn't use one.
535
573
 
@@ -157,6 +157,31 @@ System messages, context, the current turn's input, and the agent's responses ar
157
157
 
158
158
  Trimmed messages stay in storage. During agent runs, Mastra persists a per-thread boundary so they're excluded from later turns. Setting `messageHistory` without `lastMessages` disables the default 10-message cap. Set both to combine a count cap with a token budget. Set `maxTokens` to `0` to disable message history.
159
159
 
160
+ ### OpenAI Responses compaction
161
+
162
+ OpenAI Responses models can compact provider context during long-running conversations. Enable compaction for a call with `providerOptions.openai.contextManagement`:
163
+
164
+ ```typescript
165
+ await agent.stream('Continue the conversation', {
166
+ memory: {
167
+ thread: 'thread-123',
168
+ resource: 'user-456',
169
+ },
170
+ providerOptions: {
171
+ openai: {
172
+ store: false,
173
+ contextManagement: [{ type: 'compaction', compactThreshold: 10_000 }],
174
+ },
175
+ },
176
+ })
177
+ ```
178
+
179
+ When OpenAI returns a compaction item, Mastra stores it with the thread and replays it across tool loops and later agent calls. With `store: false`, Mastra retains the encrypted compaction content. With stored Responses, an item with an OpenAI item ID can replay as an `item_reference`.
180
+
181
+ Compaction state is provider-specific. Mastra removes OpenAI compaction items when a thread switches to an incompatible provider. Other stored messages remain unchanged.
182
+
183
+ When the selected history contains a compaction checkpoint, Mastra keeps the full conversation in Memory but sends OpenAI only the latest checkpoint, system instructions, and messages after that checkpoint. Memory's `lastMessages` and `messageHistory` controls still determine which stored messages are selected before compaction is applied.
184
+
160
185
  > **Tip:** When memory is enabled, [Studio](https://mastra.ai/docs/studio/overview) uses message history to display past conversations in the chat sidebar.
161
186
 
162
187
  ## Thread title generation
@@ -978,6 +978,14 @@ The standalone `ObservationalMemory` class accepts all the same options as the `
978
978
 
979
979
  **obscureThreadIds** (`boolean`): When enabled, thread IDs are hashed before being included in observation context. This prevents the LLM from recognizing patterns in thread identifiers. Automatically enabled when using resource scope through the Memory class. (Default: `false`)
980
980
 
981
+ ## Hosted observational memory
982
+
983
+ A memory implementation that runs Observational Memory itself, instead of through the `observational-memory` processor (for example a hosted backend), can extend `MastraMemory` and override these methods. Memory routes then report its settings and records. The base class returns `undefined` from each method, which means the memory doesn't provide them.
984
+
985
+ **getObservationalMemoryConfig** (`(args: { requestContext?: RequestContext }) => Promise<ObservationalMemorySettings | undefined>`): Returns the Observational Memory settings: enabled, scope (thread or resource), and optionally messageTokens and observationTokens thresholds.
986
+
987
+ **getObservationalMemoryRecords** (`(args: GetObservationalMemoryRecordsInput) => Promise<ObservationalMemoryRecords | undefined>`): Returns the current record (null before the first observation) and past generations in history, newest first. Input accepts threadId, resourceId, historyLimit, from, to, offset and requestContext. Callers check thread access before calling it.
988
+
981
989
  ## Recall tool
982
990
 
983
991
  When `retrieval` is truthy, Mastra registers a `recall` tool that pages through raw messages behind observation group ranges. With the default resource scope, the tool can list threads (`mode: "threads"`) and browse another thread through `threadId`. It also supports cross-thread search. Set `retrieval: { vector: true }` for semantic search (`mode: "search"`), or use `scope: 'thread'` to restrict the tool to the current thread. The tool is automatically added to the agent.
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_src = require("./src-DxOLwFhL.cjs");
2
+ const require_src = require("./src-Cr_776no.cjs");
3
3
  let _mastra_core_processors = require("@mastra/core/processors");
4
4
  let _mastra_core_memory = require("@mastra/core/memory");
5
5
  exports.AUTO_MODEL_BY_PROVIDER = require_src.AUTO_MODEL_BY_PROVIDER;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { m as AUTO_MODEL_BY_PROVIDER, K as Extractor, D as KnowledgeSemanticIndexCoordinator, t as Memory, n as MessageHistory, y as ModelByInputTokens, M as SUMMARIZE_THREAD_DEFAULTS, r as SemanticRecall, O as StaleKnowledgeSemanticIndexError, k as Subconscious, g as WORKING_MEMORY_STATE_ID, _ as WORKING_MEMORY_STATE_PROCESSOR_ID, i as WorkingMemory, A as WorkingMemoryExtractor, v as WorkingMemoryStateProcessor, a as asUserTurn, j as deepMergeWorkingMemory, o as escapeTurnMarkup, s as extractWorkingMemoryContent, c as extractWorkingMemoryTags, d as getObservationsAsOf, l as removeWorkingMemoryTags, h as resolveAutoModelId, u as sealTurnMarkup, N as summarizeConversation } from "./src-C6oJP8WI.js";
1
+ export { m as AUTO_MODEL_BY_PROVIDER, K as Extractor, D as KnowledgeSemanticIndexCoordinator, t as Memory, n as MessageHistory, y as ModelByInputTokens, M as SUMMARIZE_THREAD_DEFAULTS, r as SemanticRecall, O as StaleKnowledgeSemanticIndexError, k as Subconscious, g as WORKING_MEMORY_STATE_ID, _ as WORKING_MEMORY_STATE_PROCESSOR_ID, i as WorkingMemory, A as WorkingMemoryExtractor, v as WorkingMemoryStateProcessor, a as asUserTurn, j as deepMergeWorkingMemory, o as escapeTurnMarkup, s as extractWorkingMemoryContent, c as extractWorkingMemoryTags, d as getObservationsAsOf, l as removeWorkingMemoryTags, h as resolveAutoModelId, u as sealTurnMarkup, N as summarizeConversation } from "./src-SlK5VIXE.js";
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_src = require("../src-DxOLwFhL.cjs");
2
+ const require_src = require("../src-Cr_776no.cjs");
3
3
  exports.AUTO_MODEL_BY_PROVIDER = require_src.AUTO_MODEL_BY_PROVIDER;
4
4
  exports.Extractor = require_src.Extractor;
5
5
  exports.ModelByInputTokens = require_src.ModelByInputTokens;
@@ -1 +1 @@
1
- export { m as AUTO_MODEL_BY_PROVIDER, K as Extractor, y as ModelByInputTokens, q as OBSERVATIONAL_MEMORY_DEFAULTS, J as OBSERVATION_CONTEXT_INSTRUCTIONS, Y as OBSERVATION_CONTEXT_PROMPT, X as OBSERVATION_CONTEXT_PROMPT_THREAD, Z as OBSERVATION_CONTINUATION_HINT, F as OBSERVER_SYSTEM_PROMPT, p as ObservationalMemory, f as ObservationalMemoryProcessor, P as TokenCounter, A as WorkingMemoryExtractor, I as buildObserverPrompt, L as buildObserverSystemPrompt, b as combineObservationGroupRanges, x as deriveObservationGroupProvenance, R as extractCurrentTask, z as formatMessagesForObserver, Q as getObservationContextPrompt, d as getObservationsAsOf, B as hasCurrentTaskSection, U as injectAnchorIds, V as optimizeObservationsForContext, W as parseAnchorId, S as parseObservationGroups, H as parseObserverOutput, C as reconcileObservationGroupsFromReflection, w as renderObservationGroupsForReflection, h as resolveAutoModelId, G as stripEphemeralAnchorIds, T as stripObservationGroups, N as summarizeConversation, E as wrapInObservationGroup } from "../src-C6oJP8WI.js";
1
+ export { m as AUTO_MODEL_BY_PROVIDER, K as Extractor, y as ModelByInputTokens, q as OBSERVATIONAL_MEMORY_DEFAULTS, J as OBSERVATION_CONTEXT_INSTRUCTIONS, Y as OBSERVATION_CONTEXT_PROMPT, X as OBSERVATION_CONTEXT_PROMPT_THREAD, Z as OBSERVATION_CONTINUATION_HINT, F as OBSERVER_SYSTEM_PROMPT, p as ObservationalMemory, f as ObservationalMemoryProcessor, P as TokenCounter, A as WorkingMemoryExtractor, I as buildObserverPrompt, L as buildObserverSystemPrompt, b as combineObservationGroupRanges, x as deriveObservationGroupProvenance, R as extractCurrentTask, z as formatMessagesForObserver, Q as getObservationContextPrompt, d as getObservationsAsOf, B as hasCurrentTaskSection, U as injectAnchorIds, V as optimizeObservationsForContext, W as parseAnchorId, S as parseObservationGroups, H as parseObserverOutput, C as reconcileObservationGroupsFromReflection, w as renderObservationGroupsForReflection, h as resolveAutoModelId, G as stripEphemeralAnchorIds, T as stripObservationGroups, N as summarizeConversation, E as wrapInObservationGroup } from "../src-SlK5VIXE.js";
@@ -1,6 +1,11 @@
1
1
  import type { MastraDBMessage } from '@mastra/core/agent';
2
2
  /** `timeZone` when this runtime recognises it; otherwise undefined, which means the process time zone. */
3
3
  export declare function resolveTimeZone(timeZone: string | undefined): string | undefined;
4
+ /**
5
+ * A shared `en-US` formatter for `options` in `timeZone`, or in the process time zone when unset. Building a formatter
6
+ * costs far more than formatting with one, and OM formats a date for every message line. `name` identifies `options`.
7
+ */
8
+ export declare function getDateTimeFormat(name: string, timeZone: string | undefined, options: Intl.DateTimeFormatOptions): Intl.DateTimeFormat;
4
9
  /** Format an instant relative to today, using the record's calendar time zone. */
5
10
  export declare function formatRelativeTime(date: Date, currentDate: Date, timeZone?: string): string;
6
11
  /**
@@ -67,7 +67,8 @@ export declare class ObservationTurn {
67
67
  responseMessageId?: string;
68
68
  /** Processor-provided hooks for turn/step lifecycle integration. */
69
69
  readonly hooks: ObservationTurnHooks;
70
- readonly abortSignal?: AbortSignal;
70
+ /** The current call's abort signal. A durable resume continues the turn under a new call, so the processor updates it before each step. */
71
+ abortSignal?: AbortSignal;
71
72
  constructor(opts: {
72
73
  abortSignal?: AbortSignal;
73
74
  om: ObservationalMemory;
@@ -8884,7 +8884,7 @@ var object$3 = ({ schema: inputSchema }) => {
8884
8884
  }
8885
8885
  };
8886
8886
  };
8887
- // ../_vendored/ai_v6/dist/dist-BoOIE3nE.js
8887
+ // ../_vendored/ai_v6/dist/dist-BHXUQYEB.js
8888
8888
  var marker$1$10 = "vercel.ai.error";
8889
8889
  var symbol$1$13 = Symbol.for(marker$1$10);
8890
8890
  var _a$1$1;
@@ -9760,7 +9760,7 @@ function withUserAgentSuffix$1(headers, ...userAgentSuffixParts) {
9760
9760
  normalizedHeaders.set("user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" "));
9761
9761
  return Object.fromEntries(normalizedHeaders.entries());
9762
9762
  }
9763
- var VERSION$5 = "4.0.66";
9763
+ var VERSION$5 = "4.0.67";
9764
9764
  var getOriginalFetch$1 = () => globalThis.fetch;
9765
9765
  var getFromApi$1 = async ({ url, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, validateUrl, credentialedOrigin, trustedOrigin }) => {
9766
9766
  try {
@@ -10795,7 +10795,7 @@ function standardSchema$1(standardSchema2) {
10795
10795
  return addAdditionalPropertiesToJsonSchema$1(standardSchema2["~standard"].jsonSchema.input({ target: "draft-07" }));
10796
10796
  }, { validate: async (value) => {
10797
10797
  const result = await standardSchema2["~standard"].validate(value);
10798
- return "value" in result ? {
10798
+ return result.issues === void 0 && "value" in result ? {
10799
10799
  success: true,
10800
10800
  value: result.value
10801
10801
  } : {
@@ -11236,7 +11236,7 @@ var createJsonResponseHandler$1 = (responseSchema) => async ({ response, url, re
11236
11236
  function withoutTrailingSlash$1(url) {
11237
11237
  return url == null ? void 0 : url.replace(/\/$/, "");
11238
11238
  }
11239
- // ../_vendored/ai_v6/dist/dist-ByO0vuJJ.js
11239
+ // ../_vendored/ai_v6/dist/dist-CufwpBZM.js
11240
11240
  function getContext$1() {
11241
11241
  return { headers: {} };
11242
11242
  }
@@ -25504,12 +25504,30 @@ function resolveTimeZone(timeZone) {
25504
25504
  }
25505
25505
  return known ? timeZone : void 0;
25506
25506
  }
25507
+ const MAX_CACHED_FORMATTERS = 256;
25508
+ const formatters = /* @__PURE__ */ new Map();
25509
+ /**
25510
+ * A shared `en-US` formatter for `options` in `timeZone`, or in the process time zone when unset. Building a formatter
25511
+ * costs far more than formatting with one, and OM formats a date for every message line. `name` identifies `options`.
25512
+ */
25513
+ function getDateTimeFormat(name, timeZone, options) {
25514
+ const key = `${name}|${timeZone ?? `process:${globalThis.process?.env?.TZ ?? ""}`}`;
25515
+ let formatter = formatters.get(key);
25516
+ if (!formatter) {
25517
+ if (formatters.size >= MAX_CACHED_FORMATTERS) formatters.clear();
25518
+ formatter = new Intl.DateTimeFormat("en-US", {
25519
+ ...options,
25520
+ timeZone
25521
+ });
25522
+ formatters.set(key, formatter);
25523
+ }
25524
+ return formatter;
25525
+ }
25507
25526
  /** Day number of the calendar date `instant` falls on in `timeZone` (the process time zone when unset). */
25508
25527
  function calendarDayIn(instant, timeZone) {
25509
25528
  const zone = resolveTimeZone(timeZone);
25510
25529
  if (!zone) return calendarDay(instant);
25511
- const parts = new Intl.DateTimeFormat("en-US", {
25512
- timeZone: zone,
25530
+ const parts = getDateTimeFormat("calendar-day", zone, {
25513
25531
  year: "numeric",
25514
25532
  month: "numeric",
25515
25533
  day: "numeric"
@@ -25824,7 +25842,8 @@ function formatTemporalGap(diffMs) {
25824
25842
  return formatTwoUnits(year, "year", month, "month");
25825
25843
  }
25826
25844
  function formatTemporalTimestamp(date) {
25827
- return date.toLocaleString("en-US", {
25845
+ if (Number.isNaN(date.getTime())) return "Invalid Date";
25846
+ return getDateTimeFormat("temporal-timestamp", void 0, {
25828
25847
  year: "numeric",
25829
25848
  month: "2-digit",
25830
25849
  day: "2-digit",
@@ -25832,7 +25851,7 @@ function formatTemporalTimestamp(date) {
25832
25851
  minute: "2-digit",
25833
25852
  hour12: true,
25834
25853
  timeZoneName: "short"
25835
- });
25854
+ }).format(date);
25836
25855
  }
25837
25856
  function getMessagePartTimestamp(msg, position) {
25838
25857
  const timestamps = msg.content?.parts?.map((part) => "createdAt" in part ? part.createdAt : void 0).filter((timestamp) => typeof timestamp === "number");
@@ -26896,8 +26915,7 @@ const OBSERVER_IMAGE_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
26896
26915
  ]);
26897
26916
  function formatObserverDate(createdAt, timeZone) {
26898
26917
  if (!createdAt) return "";
26899
- const parts = new Intl.DateTimeFormat("en-US", {
26900
- timeZone,
26918
+ const parts = getDateTimeFormat("observer-date", timeZone, {
26901
26919
  year: "numeric",
26902
26920
  month: "short",
26903
26921
  day: "numeric"
@@ -26906,12 +26924,11 @@ function formatObserverDate(createdAt, timeZone) {
26906
26924
  return `${part("month")} ${part("day")} ${part("year")}`;
26907
26925
  }
26908
26926
  function formatObserverTime(createdAt, timeZone) {
26909
- return createdAt ? createdAt.toLocaleTimeString("en-US", {
26910
- timeZone,
26927
+ return createdAt ? getDateTimeFormat("observer-time", timeZone, {
26911
26928
  hour: "numeric",
26912
26929
  minute: "2-digit",
26913
26930
  hour12: true
26914
- }) : "";
26931
+ }).format(createdAt) : "";
26915
26932
  }
26916
26933
  function getObserverPathExtension(value) {
26917
26934
  return (value.split("#", 1)[0]?.split("?", 1)[0] ?? value).match(/\.([a-z0-9]+)$/i)?.[1]?.toLowerCase();
@@ -36018,6 +36035,7 @@ var ObservationTurn = class {
36018
36035
  responseMessageId;
36019
36036
  /** Processor-provided hooks for turn/step lifecycle integration. */
36020
36037
  hooks;
36038
+ /** The current call's abort signal. A durable resume continues the turn under a new call, so the processor updates it before each step. */
36021
36039
  abortSignal;
36022
36040
  constructor(opts) {
36023
36041
  this.abortSignal = opts.abortSignal;
@@ -39420,6 +39438,16 @@ ${formattedMessages}
39420
39438
  let skipped = 0;
39421
39439
  let backoffTriggered = false;
39422
39440
  const retentionCounter = typeof retentionFloor === "number" ? new TokenCounter() : null;
39441
+ const tokensById = /* @__PURE__ */ new Map();
39442
+ let remainingTokens = 0;
39443
+ let remainingIds = 0;
39444
+ if (retentionCounter) {
39445
+ const countable = messages.filter((m) => m?.id && m.id !== "om-continuation");
39446
+ remainingTokens = retentionCounter.countMessages(countable);
39447
+ for (const m of countable) tokensById.set(m.id, (tokensById.get(m.id) ?? 0) + retentionCounter.countMessage(m));
39448
+ remainingIds = tokensById.size;
39449
+ }
39450
+ const remainingCount = (tokens, ids) => ids === 0 ? 0 : tokens;
39423
39451
  for (const msg of messages) {
39424
39452
  if (!msg?.id || msg.id === "om-continuation" || !observedSet.has(msg.id)) continue;
39425
39453
  if (preserveSet?.has(msg.id)) {
@@ -39429,31 +39457,40 @@ ${formattedMessages}
39429
39457
  const unobservedParts = getUnobservedParts(msg);
39430
39458
  const totalParts = msg.content?.parts?.length ?? 0;
39431
39459
  if (unobservedParts.length > 0 && unobservedParts.length < totalParts) {
39460
+ const tokensBefore = retentionCounter ? retentionCounter.countMessage(msg) : 0;
39432
39461
  msg.content.parts = unobservedParts;
39462
+ if (retentionCounter) {
39463
+ const delta = retentionCounter.countMessage(msg) - tokensBefore;
39464
+ tokensById.set(msg.id, (tokensById.get(msg.id) ?? 0) + delta);
39465
+ if (!idsToRemove.has(msg.id)) remainingTokens += delta;
39466
+ }
39433
39467
  continue;
39434
39468
  }
39469
+ const alreadyRemoved = idsToRemove.has(msg.id);
39470
+ const msgTokens = tokensById.get(msg.id) ?? 0;
39435
39471
  if (retentionCounter && typeof retentionFloor === "number") {
39436
- const nextRemainingMessages = messages.filter((m) => m?.id && m.id !== "om-continuation" && !idsToRemove.has(m.id) && m.id !== msg.id);
39437
- if (retentionCounter.countMessages(nextRemainingMessages) < retentionFloor) {
39472
+ const idsIfRemoved = alreadyRemoved ? remainingIds : remainingIds - 1;
39473
+ if (remainingCount(alreadyRemoved ? remainingTokens : remainingTokens - msgTokens, idsIfRemoved) < retentionFloor) {
39438
39474
  skipped += 1;
39439
39475
  backoffTriggered = true;
39440
39476
  break;
39441
39477
  }
39442
39478
  }
39479
+ if (!alreadyRemoved) {
39480
+ remainingTokens -= msgTokens;
39481
+ remainingIds -= 1;
39482
+ }
39443
39483
  idsToRemove.add(msg.id);
39444
39484
  removalOrder.push(msg.id);
39445
39485
  }
39446
- if (retentionCounter && typeof retentionFloor === "number" && idsToRemove.size > 0) {
39447
- let remainingMessages = messages.filter((m) => m?.id && m.id !== "om-continuation" && !idsToRemove.has(m.id));
39448
- let remainingTokens = retentionCounter.countMessages(remainingMessages);
39449
- while (remainingTokens < retentionFloor && removalOrder.length > 0) {
39450
- const restoreId = removalOrder.pop();
39451
- idsToRemove.delete(restoreId);
39452
- skipped += 1;
39453
- backoffTriggered = true;
39454
- remainingMessages = messages.filter((m) => m?.id && m.id !== "om-continuation" && !idsToRemove.has(m.id));
39455
- remainingTokens = retentionCounter.countMessages(remainingMessages);
39486
+ if (retentionCounter && typeof retentionFloor === "number" && idsToRemove.size > 0) while (remainingCount(remainingTokens, remainingIds) < retentionFloor && removalOrder.length > 0) {
39487
+ const restoreId = removalOrder.pop();
39488
+ if (idsToRemove.delete(restoreId)) {
39489
+ remainingTokens += tokensById.get(restoreId) ?? 0;
39490
+ remainingIds += 1;
39456
39491
  }
39492
+ skipped += 1;
39493
+ backoffTriggered = true;
39457
39494
  }
39458
39495
  omDebug(`[OM:cleanupActivation] matched=${idsToRemove.size}, skipped=${skipped}, backoffTriggered=${backoffTriggered}`);
39459
39496
  return [...idsToRemove];
@@ -41065,6 +41102,7 @@ var ObservationalMemoryProcessor = class {
41065
41102
  const observabilityContext = getOmObservabilityContext(args);
41066
41103
  state.__omObservabilityContext = observabilityContext;
41067
41104
  this.turn.observabilityContext = observabilityContext;
41105
+ this.turn.abortSignal = abortSignal;
41068
41106
  this.turn.actorModelContext = actorModelContext;
41069
41107
  this.turn.responseMessageId = responseMessageId;
41070
41108
  {
@@ -41456,6 +41494,27 @@ const invalidMerge = (text) => new _mastra_core_error.MastraError({
41456
41494
  category: _mastra_core_error.ErrorCategory.USER,
41457
41495
  text
41458
41496
  });
41497
+ /**
41498
+ * Whether a processor with `id` is configured, either at the top level or as a step
41499
+ * anywhere inside a processor workflow (sequential, branch, parallel, loop, foreach, nested workflow).
41500
+ * Workflow steps built with `createStep(processor)` carry `processorId`, which survives step id
41501
+ * rewrites (the Editor renames graph steps to `processor:<graph step id>`); older core versions
41502
+ * only carry the id `processor:<id>`.
41503
+ * A step inside a branch counts even though it only runs when that branch is taken.
41504
+ */
41505
+ function hasConfiguredProcessorId(processors, id) {
41506
+ const seen = /* @__PURE__ */ new Set();
41507
+ const matchesStep = (step) => {
41508
+ if (!step || typeof step !== "object" || seen.has(step)) return false;
41509
+ seen.add(step);
41510
+ const { processorId, id: stepId, stepGraph } = step;
41511
+ if (Array.isArray(stepGraph)) return stepGraph.some(matchesEntry);
41512
+ return processorId !== void 0 ? processorId === id : stepId === `processor:${id}`;
41513
+ };
41514
+ const isEntry = (value) => !!value && typeof value === "object" && "type" in value && "step" in value;
41515
+ const matchesEntry = (entry) => (isEntry(entry.step) ? matchesEntry(entry.step) : matchesStep(entry.step)) || (entry.steps ?? []).some(matchesEntry);
41516
+ return processors.some((processor) => (0, _mastra_core_processors.isProcessorWorkflow)(processor) ? matchesStep(processor) : processor.id === id);
41517
+ }
41459
41518
  var Memory = class Memory extends _mastra_core_memory.MastraMemory {
41460
41519
  createMemoryTokenCounter() {
41461
41520
  return new TokenCounter();
@@ -43745,7 +43804,7 @@ Notes:
43745
43804
  */
43746
43805
  async getErrorProcessors(configuredProcessors = [], context) {
43747
43806
  const processors = await super.getErrorProcessors(configuredProcessors, context);
43748
- const om = await this.createOMProcessor(configuredProcessors, context);
43807
+ const om = await this.createOMProcessor(configuredProcessors.filter((p) => !(0, _mastra_core_processors.isProcessorWorkflow)(p)), context);
43749
43808
  if (om) processors.push(om);
43750
43809
  return processors;
43751
43810
  }
@@ -43755,7 +43814,7 @@ Notes:
43755
43814
  * in the user's configured processors.
43756
43815
  */
43757
43816
  async createOMProcessor(configuredProcessors = [], context) {
43758
- if (configuredProcessors.some((p) => !("workflow" in p) && p.id === "observational-memory")) return null;
43817
+ if (hasConfiguredProcessorId(configuredProcessors, "observational-memory")) return null;
43759
43818
  const runtimeMemory = context?.get("MastraMemory");
43760
43819
  const runtimeObservationalMemory = normalizeObservationalMemoryConfig(runtimeMemory?.memoryConfig?.observationalMemory);
43761
43820
  const effectiveConfig = normalizeObservationalMemoryConfig((runtimeMemory?.memoryConfig?.observationalMemory !== void 0 ? this.getMergedThreadConfig({
@@ -10,7 +10,7 @@ import { coreFeatures } from "@mastra/core/features";
10
10
  import { MESSAGE_EMBEDDING_CHARS_PER_TOKEN, MastraMemory, asUserTurn, buildMessageEmbeddingRows, chunkMessageText, escapeTurnMarkup, getMemoryTokenBoundary, getThreadOMMetadata, isAfterMemoryTokenBoundary, isThreadTitlePinned, loadMessageHistory, normalizeMessageHistoryConfig, parseMemoryRequestContext, resolveMaxChunkChars, sealTurnMarkup, setThreadOMMetadata, upsertMessageVectors } from "@mastra/core/memory";
11
11
  import * as coreObservability from "@mastra/core/observability";
12
12
  import { EntityType, SpanType, createObservabilityContext, getOrCreateSpan } from "@mastra/core/observability";
13
- import { MessageHistory, MessageHistory as MessageHistory$1, SemanticRecall, TokenLimiterProcessor, WorkingMemory } from "@mastra/core/processors";
13
+ import { MessageHistory, MessageHistory as MessageHistory$1, SemanticRecall, TokenLimiterProcessor, WorkingMemory, isProcessorWorkflow } from "@mastra/core/processors";
14
14
  import { generateEmptyFromSchema } from "@mastra/core/utils";
15
15
  import { isStandardSchemaWithJSON, standardSchemaToJSONSchema, toStandardSchema } from "@mastra/schema-compat/schema";
16
16
  import { Mutex } from "async-mutex";
@@ -8862,7 +8862,7 @@ var object$2 = ({ schema: inputSchema }) => {
8862
8862
  }
8863
8863
  };
8864
8864
  };
8865
- // ../_vendored/ai_v6/dist/dist-BoOIE3nE.js
8865
+ // ../_vendored/ai_v6/dist/dist-BHXUQYEB.js
8866
8866
  var marker$1$10 = "vercel.ai.error";
8867
8867
  var symbol$1$13 = Symbol.for(marker$1$10);
8868
8868
  var _a$1$1;
@@ -9738,7 +9738,7 @@ function withUserAgentSuffix$1(headers, ...userAgentSuffixParts) {
9738
9738
  normalizedHeaders.set("user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" "));
9739
9739
  return Object.fromEntries(normalizedHeaders.entries());
9740
9740
  }
9741
- var VERSION$5 = "4.0.66";
9741
+ var VERSION$5 = "4.0.67";
9742
9742
  var getOriginalFetch$1 = () => globalThis.fetch;
9743
9743
  var getFromApi$1 = async ({ url, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, validateUrl, credentialedOrigin, trustedOrigin }) => {
9744
9744
  try {
@@ -10773,7 +10773,7 @@ function standardSchema$1(standardSchema2) {
10773
10773
  return addAdditionalPropertiesToJsonSchema$1(standardSchema2["~standard"].jsonSchema.input({ target: "draft-07" }));
10774
10774
  }, { validate: async (value) => {
10775
10775
  const result = await standardSchema2["~standard"].validate(value);
10776
- return "value" in result ? {
10776
+ return result.issues === void 0 && "value" in result ? {
10777
10777
  success: true,
10778
10778
  value: result.value
10779
10779
  } : {
@@ -11214,7 +11214,7 @@ var createJsonResponseHandler$1 = (responseSchema) => async ({ response, url, re
11214
11214
  function withoutTrailingSlash$1(url) {
11215
11215
  return url == null ? void 0 : url.replace(/\/$/, "");
11216
11216
  }
11217
- // ../_vendored/ai_v6/dist/dist-ByO0vuJJ.js
11217
+ // ../_vendored/ai_v6/dist/dist-CufwpBZM.js
11218
11218
  function getContext$1() {
11219
11219
  return { headers: {} };
11220
11220
  }
@@ -25482,12 +25482,30 @@ function resolveTimeZone(timeZone) {
25482
25482
  }
25483
25483
  return known ? timeZone : void 0;
25484
25484
  }
25485
+ const MAX_CACHED_FORMATTERS = 256;
25486
+ const formatters = /* @__PURE__ */ new Map();
25487
+ /**
25488
+ * A shared `en-US` formatter for `options` in `timeZone`, or in the process time zone when unset. Building a formatter
25489
+ * costs far more than formatting with one, and OM formats a date for every message line. `name` identifies `options`.
25490
+ */
25491
+ function getDateTimeFormat(name, timeZone, options) {
25492
+ const key = `${name}|${timeZone ?? `process:${globalThis.process?.env?.TZ ?? ""}`}`;
25493
+ let formatter = formatters.get(key);
25494
+ if (!formatter) {
25495
+ if (formatters.size >= MAX_CACHED_FORMATTERS) formatters.clear();
25496
+ formatter = new Intl.DateTimeFormat("en-US", {
25497
+ ...options,
25498
+ timeZone
25499
+ });
25500
+ formatters.set(key, formatter);
25501
+ }
25502
+ return formatter;
25503
+ }
25485
25504
  /** Day number of the calendar date `instant` falls on in `timeZone` (the process time zone when unset). */
25486
25505
  function calendarDayIn(instant, timeZone) {
25487
25506
  const zone = resolveTimeZone(timeZone);
25488
25507
  if (!zone) return calendarDay(instant);
25489
- const parts = new Intl.DateTimeFormat("en-US", {
25490
- timeZone: zone,
25508
+ const parts = getDateTimeFormat("calendar-day", zone, {
25491
25509
  year: "numeric",
25492
25510
  month: "numeric",
25493
25511
  day: "numeric"
@@ -25802,7 +25820,8 @@ function formatTemporalGap(diffMs) {
25802
25820
  return formatTwoUnits(year, "year", month, "month");
25803
25821
  }
25804
25822
  function formatTemporalTimestamp(date) {
25805
- return date.toLocaleString("en-US", {
25823
+ if (Number.isNaN(date.getTime())) return "Invalid Date";
25824
+ return getDateTimeFormat("temporal-timestamp", void 0, {
25806
25825
  year: "numeric",
25807
25826
  month: "2-digit",
25808
25827
  day: "2-digit",
@@ -25810,7 +25829,7 @@ function formatTemporalTimestamp(date) {
25810
25829
  minute: "2-digit",
25811
25830
  hour12: true,
25812
25831
  timeZoneName: "short"
25813
- });
25832
+ }).format(date);
25814
25833
  }
25815
25834
  function getMessagePartTimestamp(msg, position) {
25816
25835
  const timestamps = msg.content?.parts?.map((part) => "createdAt" in part ? part.createdAt : void 0).filter((timestamp) => typeof timestamp === "number");
@@ -26874,8 +26893,7 @@ const OBSERVER_IMAGE_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
26874
26893
  ]);
26875
26894
  function formatObserverDate(createdAt, timeZone) {
26876
26895
  if (!createdAt) return "";
26877
- const parts = new Intl.DateTimeFormat("en-US", {
26878
- timeZone,
26896
+ const parts = getDateTimeFormat("observer-date", timeZone, {
26879
26897
  year: "numeric",
26880
26898
  month: "short",
26881
26899
  day: "numeric"
@@ -26884,12 +26902,11 @@ function formatObserverDate(createdAt, timeZone) {
26884
26902
  return `${part("month")} ${part("day")} ${part("year")}`;
26885
26903
  }
26886
26904
  function formatObserverTime(createdAt, timeZone) {
26887
- return createdAt ? createdAt.toLocaleTimeString("en-US", {
26888
- timeZone,
26905
+ return createdAt ? getDateTimeFormat("observer-time", timeZone, {
26889
26906
  hour: "numeric",
26890
26907
  minute: "2-digit",
26891
26908
  hour12: true
26892
- }) : "";
26909
+ }).format(createdAt) : "";
26893
26910
  }
26894
26911
  function getObserverPathExtension(value) {
26895
26912
  return (value.split("#", 1)[0]?.split("?", 1)[0] ?? value).match(/\.([a-z0-9]+)$/i)?.[1]?.toLowerCase();
@@ -35996,6 +36013,7 @@ var ObservationTurn = class {
35996
36013
  responseMessageId;
35997
36014
  /** Processor-provided hooks for turn/step lifecycle integration. */
35998
36015
  hooks;
36016
+ /** The current call's abort signal. A durable resume continues the turn under a new call, so the processor updates it before each step. */
35999
36017
  abortSignal;
36000
36018
  constructor(opts) {
36001
36019
  this.abortSignal = opts.abortSignal;
@@ -39398,6 +39416,16 @@ ${formattedMessages}
39398
39416
  let skipped = 0;
39399
39417
  let backoffTriggered = false;
39400
39418
  const retentionCounter = typeof retentionFloor === "number" ? new TokenCounter() : null;
39419
+ const tokensById = /* @__PURE__ */ new Map();
39420
+ let remainingTokens = 0;
39421
+ let remainingIds = 0;
39422
+ if (retentionCounter) {
39423
+ const countable = messages.filter((m) => m?.id && m.id !== "om-continuation");
39424
+ remainingTokens = retentionCounter.countMessages(countable);
39425
+ for (const m of countable) tokensById.set(m.id, (tokensById.get(m.id) ?? 0) + retentionCounter.countMessage(m));
39426
+ remainingIds = tokensById.size;
39427
+ }
39428
+ const remainingCount = (tokens, ids) => ids === 0 ? 0 : tokens;
39401
39429
  for (const msg of messages) {
39402
39430
  if (!msg?.id || msg.id === "om-continuation" || !observedSet.has(msg.id)) continue;
39403
39431
  if (preserveSet?.has(msg.id)) {
@@ -39407,31 +39435,40 @@ ${formattedMessages}
39407
39435
  const unobservedParts = getUnobservedParts(msg);
39408
39436
  const totalParts = msg.content?.parts?.length ?? 0;
39409
39437
  if (unobservedParts.length > 0 && unobservedParts.length < totalParts) {
39438
+ const tokensBefore = retentionCounter ? retentionCounter.countMessage(msg) : 0;
39410
39439
  msg.content.parts = unobservedParts;
39440
+ if (retentionCounter) {
39441
+ const delta = retentionCounter.countMessage(msg) - tokensBefore;
39442
+ tokensById.set(msg.id, (tokensById.get(msg.id) ?? 0) + delta);
39443
+ if (!idsToRemove.has(msg.id)) remainingTokens += delta;
39444
+ }
39411
39445
  continue;
39412
39446
  }
39447
+ const alreadyRemoved = idsToRemove.has(msg.id);
39448
+ const msgTokens = tokensById.get(msg.id) ?? 0;
39413
39449
  if (retentionCounter && typeof retentionFloor === "number") {
39414
- const nextRemainingMessages = messages.filter((m) => m?.id && m.id !== "om-continuation" && !idsToRemove.has(m.id) && m.id !== msg.id);
39415
- if (retentionCounter.countMessages(nextRemainingMessages) < retentionFloor) {
39450
+ const idsIfRemoved = alreadyRemoved ? remainingIds : remainingIds - 1;
39451
+ if (remainingCount(alreadyRemoved ? remainingTokens : remainingTokens - msgTokens, idsIfRemoved) < retentionFloor) {
39416
39452
  skipped += 1;
39417
39453
  backoffTriggered = true;
39418
39454
  break;
39419
39455
  }
39420
39456
  }
39457
+ if (!alreadyRemoved) {
39458
+ remainingTokens -= msgTokens;
39459
+ remainingIds -= 1;
39460
+ }
39421
39461
  idsToRemove.add(msg.id);
39422
39462
  removalOrder.push(msg.id);
39423
39463
  }
39424
- if (retentionCounter && typeof retentionFloor === "number" && idsToRemove.size > 0) {
39425
- let remainingMessages = messages.filter((m) => m?.id && m.id !== "om-continuation" && !idsToRemove.has(m.id));
39426
- let remainingTokens = retentionCounter.countMessages(remainingMessages);
39427
- while (remainingTokens < retentionFloor && removalOrder.length > 0) {
39428
- const restoreId = removalOrder.pop();
39429
- idsToRemove.delete(restoreId);
39430
- skipped += 1;
39431
- backoffTriggered = true;
39432
- remainingMessages = messages.filter((m) => m?.id && m.id !== "om-continuation" && !idsToRemove.has(m.id));
39433
- remainingTokens = retentionCounter.countMessages(remainingMessages);
39464
+ if (retentionCounter && typeof retentionFloor === "number" && idsToRemove.size > 0) while (remainingCount(remainingTokens, remainingIds) < retentionFloor && removalOrder.length > 0) {
39465
+ const restoreId = removalOrder.pop();
39466
+ if (idsToRemove.delete(restoreId)) {
39467
+ remainingTokens += tokensById.get(restoreId) ?? 0;
39468
+ remainingIds += 1;
39434
39469
  }
39470
+ skipped += 1;
39471
+ backoffTriggered = true;
39435
39472
  }
39436
39473
  omDebug(`[OM:cleanupActivation] matched=${idsToRemove.size}, skipped=${skipped}, backoffTriggered=${backoffTriggered}`);
39437
39474
  return [...idsToRemove];
@@ -41043,6 +41080,7 @@ var ObservationalMemoryProcessor = class {
41043
41080
  const observabilityContext = getOmObservabilityContext(args);
41044
41081
  state.__omObservabilityContext = observabilityContext;
41045
41082
  this.turn.observabilityContext = observabilityContext;
41083
+ this.turn.abortSignal = abortSignal;
41046
41084
  this.turn.actorModelContext = actorModelContext;
41047
41085
  this.turn.responseMessageId = responseMessageId;
41048
41086
  {
@@ -41434,6 +41472,27 @@ const invalidMerge = (text) => new MastraError({
41434
41472
  category: ErrorCategory.USER,
41435
41473
  text
41436
41474
  });
41475
+ /**
41476
+ * Whether a processor with `id` is configured, either at the top level or as a step
41477
+ * anywhere inside a processor workflow (sequential, branch, parallel, loop, foreach, nested workflow).
41478
+ * Workflow steps built with `createStep(processor)` carry `processorId`, which survives step id
41479
+ * rewrites (the Editor renames graph steps to `processor:<graph step id>`); older core versions
41480
+ * only carry the id `processor:<id>`.
41481
+ * A step inside a branch counts even though it only runs when that branch is taken.
41482
+ */
41483
+ function hasConfiguredProcessorId(processors, id) {
41484
+ const seen = /* @__PURE__ */ new Set();
41485
+ const matchesStep = (step) => {
41486
+ if (!step || typeof step !== "object" || seen.has(step)) return false;
41487
+ seen.add(step);
41488
+ const { processorId, id: stepId, stepGraph } = step;
41489
+ if (Array.isArray(stepGraph)) return stepGraph.some(matchesEntry);
41490
+ return processorId !== void 0 ? processorId === id : stepId === `processor:${id}`;
41491
+ };
41492
+ const isEntry = (value) => !!value && typeof value === "object" && "type" in value && "step" in value;
41493
+ const matchesEntry = (entry) => (isEntry(entry.step) ? matchesEntry(entry.step) : matchesStep(entry.step)) || (entry.steps ?? []).some(matchesEntry);
41494
+ return processors.some((processor) => isProcessorWorkflow(processor) ? matchesStep(processor) : processor.id === id);
41495
+ }
41437
41496
  var Memory = class Memory extends MastraMemory {
41438
41497
  createMemoryTokenCounter() {
41439
41498
  return new TokenCounter();
@@ -43723,7 +43782,7 @@ Notes:
43723
43782
  */
43724
43783
  async getErrorProcessors(configuredProcessors = [], context) {
43725
43784
  const processors = await super.getErrorProcessors(configuredProcessors, context);
43726
- const om = await this.createOMProcessor(configuredProcessors, context);
43785
+ const om = await this.createOMProcessor(configuredProcessors.filter((p) => !isProcessorWorkflow(p)), context);
43727
43786
  if (om) processors.push(om);
43728
43787
  return processors;
43729
43788
  }
@@ -43733,7 +43792,7 @@ Notes:
43733
43792
  * in the user's configured processors.
43734
43793
  */
43735
43794
  async createOMProcessor(configuredProcessors = [], context) {
43736
- if (configuredProcessors.some((p) => !("workflow" in p) && p.id === "observational-memory")) return null;
43795
+ if (hasConfiguredProcessorId(configuredProcessors, "observational-memory")) return null;
43737
43796
  const runtimeMemory = context?.get("MastraMemory");
43738
43797
  const runtimeObservationalMemory = normalizeObservationalMemoryConfig(runtimeMemory?.memoryConfig?.observationalMemory);
43739
43798
  const effectiveConfig = normalizeObservationalMemoryConfig((runtimeMemory?.memoryConfig?.observationalMemory !== void 0 ? this.getMergedThreadConfig({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/memory",
3
- "version": "1.41.3",
3
+ "version": "1.41.4-alpha.1",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -68,12 +68,12 @@
68
68
  "typescript": "^6.0.3",
69
69
  "vitest": "5.1.0",
70
70
  "@internal/ai-sdk-v4": "0.0.99",
71
- "@internal/ai-v7": "0.0.99",
72
- "@internal/ai-v6": "0.0.99",
73
71
  "@internal/ai-sdk-v5": "0.0.99",
72
+ "@internal/ai-v6": "0.0.99",
73
+ "@internal/ai-v7": "0.0.99",
74
74
  "@internal/lint": "0.0.152",
75
- "@mastra/core": "1.86.0",
76
- "@internal/types-builder": "0.0.127"
75
+ "@internal/types-builder": "0.0.127",
76
+ "@mastra/core": "1.87.0-alpha.8"
77
77
  },
78
78
  "peerDependencies": {
79
79
  "@mastra/core": ">=1.85.1-0 <2.0.0-0"