@mastra/memory 1.41.4-alpha.0 → 1.42.0-alpha.2

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.4-alpha.0"
6
+ version: "1.42.0-alpha.2"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,243 +1,243 @@
1
1
  {
2
- "version": "1.41.4-alpha.0",
2
+ "version": "1.42.0-alpha.2",
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-BLtNRhqm.js",
7
+ "implementation": "dist/src-Bv05c6Nj.js",
8
8
  "line": 32945
9
9
  },
10
10
  "Extractor": {
11
11
  "types": "dist/processors/observational-memory/extractor.d.ts",
12
- "implementation": "dist/src-BLtNRhqm.js",
12
+ "implementation": "dist/src-Bv05c6Nj.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-BLtNRhqm.js",
17
+ "implementation": "dist/src-Bv05c6Nj.js",
18
18
  "line": 32728
19
19
  },
20
20
  "OBSERVATIONAL_MEMORY_DEFAULTS": {
21
21
  "types": "dist/processors/observational-memory/constants.d.ts",
22
- "implementation": "dist/src-BLtNRhqm.js",
22
+ "implementation": "dist/src-Bv05c6Nj.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-BLtNRhqm.js",
27
+ "implementation": "dist/src-Bv05c6Nj.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-BLtNRhqm.js",
32
+ "implementation": "dist/src-Bv05c6Nj.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-BLtNRhqm.js",
37
+ "implementation": "dist/src-Bv05c6Nj.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-BLtNRhqm.js",
42
+ "implementation": "dist/src-Bv05c6Nj.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-BLtNRhqm.js",
47
+ "implementation": "dist/src-Bv05c6Nj.js",
48
48
  "line": 26880
49
49
  },
50
50
  "ObservationalMemory": {
51
51
  "types": "dist/processors/observational-memory/observational-memory.d.ts",
52
- "implementation": "dist/src-BLtNRhqm.js",
53
- "line": 38062
52
+ "implementation": "dist/src-Bv05c6Nj.js",
53
+ "line": 38063
54
54
  },
55
55
  "ObservationalMemoryProcessor": {
56
56
  "types": "dist/processors/observational-memory/processor.d.ts",
57
- "implementation": "dist/src-BLtNRhqm.js",
58
- "line": 40878
57
+ "implementation": "dist/src-Bv05c6Nj.js",
58
+ "line": 40897
59
59
  },
60
60
  "TokenCounter": {
61
61
  "types": "dist/processors/observational-memory/token-counter.d.ts",
62
- "implementation": "dist/src-BLtNRhqm.js",
62
+ "implementation": "dist/src-Bv05c6Nj.js",
63
63
  "line": 29410
64
64
  },
65
65
  "WorkingMemoryExtractor": {
66
66
  "types": "dist/processors/observational-memory/working-memory-extractor.d.ts",
67
- "implementation": "dist/src-BLtNRhqm.js",
67
+ "implementation": "dist/src-Bv05c6Nj.js",
68
68
  "line": 30466
69
69
  },
70
70
  "buildObserverPrompt": {
71
71
  "types": "dist/processors/observational-memory/observer-agent.d.ts",
72
- "implementation": "dist/src-BLtNRhqm.js",
72
+ "implementation": "dist/src-Bv05c6Nj.js",
73
73
  "line": 27562
74
74
  },
75
75
  "buildObserverSystemPrompt": {
76
76
  "types": "dist/processors/observational-memory/observer-agent.d.ts",
77
- "implementation": "dist/src-BLtNRhqm.js",
77
+ "implementation": "dist/src-Bv05c6Nj.js",
78
78
  "line": 26774
79
79
  },
80
80
  "combineObservationGroupRanges": {
81
81
  "types": "dist/processors/observational-memory/observation-groups.d.ts",
82
- "implementation": "dist/src-BLtNRhqm.js",
82
+ "implementation": "dist/src-Bv05c6Nj.js",
83
83
  "line": 31048
84
84
  },
85
85
  "deriveObservationGroupProvenance": {
86
86
  "types": "dist/processors/observational-memory/observation-groups.d.ts",
87
- "implementation": "dist/src-BLtNRhqm.js",
87
+ "implementation": "dist/src-Bv05c6Nj.js",
88
88
  "line": 31092
89
89
  },
90
90
  "extractCurrentTask": {
91
91
  "types": "dist/processors/observational-memory/observer-agent.d.ts",
92
- "implementation": "dist/src-BLtNRhqm.js",
92
+ "implementation": "dist/src-Bv05c6Nj.js",
93
93
  "line": 27875
94
94
  },
95
95
  "formatMessagesForObserver": {
96
96
  "types": "dist/processors/observational-memory/observer-agent.d.ts",
97
- "implementation": "dist/src-BLtNRhqm.js",
97
+ "implementation": "dist/src-Bv05c6Nj.js",
98
98
  "line": 27313
99
99
  },
100
100
  "getObservationContextPrompt": {
101
101
  "types": "dist/processors/observational-memory/constants.d.ts",
102
- "implementation": "dist/src-BLtNRhqm.js",
102
+ "implementation": "dist/src-Bv05c6Nj.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-BLtNRhqm.js",
108
- "line": 41223
107
+ "implementation": "dist/src-Bv05c6Nj.js",
108
+ "line": 41243
109
109
  },
110
110
  "hasCurrentTaskSection": {
111
111
  "types": "dist/processors/observational-memory/observer-agent.d.ts",
112
- "implementation": "dist/src-BLtNRhqm.js",
112
+ "implementation": "dist/src-Bv05c6Nj.js",
113
113
  "line": 27863
114
114
  },
115
115
  "injectAnchorIds": {
116
116
  "types": "dist/processors/observational-memory/anchor-ids.d.ts",
117
- "implementation": "dist/src-BLtNRhqm.js",
117
+ "implementation": "dist/src-Bv05c6Nj.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-BLtNRhqm.js",
122
+ "implementation": "dist/src-Bv05c6Nj.js",
123
123
  "line": 27896
124
124
  },
125
125
  "parseAnchorId": {
126
126
  "types": "dist/processors/observational-memory/anchor-ids.d.ts",
127
- "implementation": "dist/src-BLtNRhqm.js",
127
+ "implementation": "dist/src-Bv05c6Nj.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-BLtNRhqm.js",
132
+ "implementation": "dist/src-Bv05c6Nj.js",
133
133
  "line": 31003
134
134
  },
135
135
  "parseObserverOutput": {
136
136
  "types": "dist/processors/observational-memory/observer-agent.d.ts",
137
- "implementation": "dist/src-BLtNRhqm.js",
137
+ "implementation": "dist/src-Bv05c6Nj.js",
138
138
  "line": 27573
139
139
  },
140
140
  "reconcileObservationGroupsFromReflection": {
141
141
  "types": "dist/processors/observational-memory/observation-groups.d.ts",
142
- "implementation": "dist/src-BLtNRhqm.js",
142
+ "implementation": "dist/src-Bv05c6Nj.js",
143
143
  "line": 31111
144
144
  },
145
145
  "renderObservationGroupsForReflection": {
146
146
  "types": "dist/processors/observational-memory/observation-groups.d.ts",
147
- "implementation": "dist/src-BLtNRhqm.js",
147
+ "implementation": "dist/src-Bv05c6Nj.js",
148
148
  "line": 31077
149
149
  },
150
150
  "resolveAutoModelId": {
151
151
  "types": "dist/processors/observational-memory/auto-model.d.ts",
152
- "implementation": "dist/src-BLtNRhqm.js",
152
+ "implementation": "dist/src-Bv05c6Nj.js",
153
153
  "line": 32965
154
154
  },
155
155
  "stripEphemeralAnchorIds": {
156
156
  "types": "dist/processors/observational-memory/anchor-ids.d.ts",
157
- "implementation": "dist/src-BLtNRhqm.js",
157
+ "implementation": "dist/src-Bv05c6Nj.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-BLtNRhqm.js",
162
+ "implementation": "dist/src-Bv05c6Nj.js",
163
163
  "line": 31020
164
164
  },
165
165
  "summarizeConversation": {
166
166
  "types": "dist/processors/observational-memory/summarize.d.ts",
167
- "implementation": "dist/src-BLtNRhqm.js",
167
+ "implementation": "dist/src-Bv05c6Nj.js",
168
168
  "line": 30078
169
169
  },
170
170
  "wrapInObservationGroup": {
171
171
  "types": "dist/processors/observational-memory/observation-groups.d.ts",
172
- "implementation": "dist/src-BLtNRhqm.js",
172
+ "implementation": "dist/src-Bv05c6Nj.js",
173
173
  "line": 30974
174
174
  },
175
175
  "KnowledgeSemanticIndexCoordinator": {
176
176
  "types": "dist/removed-subconscious.d.ts",
177
- "implementation": "dist/src-BLtNRhqm.js",
177
+ "implementation": "dist/src-Bv05c6Nj.js",
178
178
  "line": 30572
179
179
  },
180
180
  "Memory": {
181
181
  "types": "dist/index.d.ts",
182
- "implementation": "dist/src-BLtNRhqm.js",
183
- "line": 41475
182
+ "implementation": "dist/src-Bv05c6Nj.js",
183
+ "line": 41495
184
184
  },
185
185
  "SUMMARIZE_THREAD_DEFAULTS": {
186
186
  "types": "dist/processors/observational-memory/summarize.d.ts",
187
- "implementation": "dist/src-BLtNRhqm.js",
187
+ "implementation": "dist/src-Bv05c6Nj.js",
188
188
  "line": 30034
189
189
  },
190
190
  "StaleKnowledgeSemanticIndexError": {
191
191
  "types": "dist/removed-subconscious.d.ts",
192
- "implementation": "dist/src-BLtNRhqm.js",
192
+ "implementation": "dist/src-Bv05c6Nj.js",
193
193
  "line": 30578
194
194
  },
195
195
  "Subconscious": {
196
196
  "types": "dist/removed-subconscious.d.ts",
197
- "implementation": "dist/src-BLtNRhqm.js",
197
+ "implementation": "dist/src-Bv05c6Nj.js",
198
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-BLtNRhqm.js",
202
+ "implementation": "dist/src-Bv05c6Nj.js",
203
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-BLtNRhqm.js",
207
+ "implementation": "dist/src-Bv05c6Nj.js",
208
208
  "line": 32775
209
209
  },
210
210
  "WorkingMemoryStateProcessor": {
211
211
  "types": "dist/processors/working-memory-state/processor.d.ts",
212
- "implementation": "dist/src-BLtNRhqm.js",
212
+ "implementation": "dist/src-Bv05c6Nj.js",
213
213
  "line": 32776
214
214
  },
215
215
  "deepMergeWorkingMemory": {
216
216
  "types": "dist/tools/working-memory.d.ts",
217
- "implementation": "dist/src-BLtNRhqm.js",
217
+ "implementation": "dist/src-Bv05c6Nj.js",
218
218
  "line": 30157
219
219
  },
220
220
  "extractWorkingMemoryContent": {
221
221
  "types": "dist/index.d.ts",
222
- "implementation": "dist/src-BLtNRhqm.js",
223
- "line": 41288
222
+ "implementation": "dist/src-Bv05c6Nj.js",
223
+ "line": 41308
224
224
  },
225
225
  "extractWorkingMemoryTags": {
226
226
  "types": "dist/index.d.ts",
227
- "implementation": "dist/src-BLtNRhqm.js",
228
- "line": 41256
227
+ "implementation": "dist/src-Bv05c6Nj.js",
228
+ "line": 41276
229
229
  },
230
230
  "removeWorkingMemoryTags": {
231
231
  "types": "dist/index.d.ts",
232
- "implementation": "dist/src-BLtNRhqm.js",
233
- "line": 41269
232
+ "implementation": "dist/src-Bv05c6Nj.js",
233
+ "line": 41289
234
234
  }
235
235
  },
236
236
  "modules": {
237
237
  "processors": {
238
238
  "index": "dist/processors/index.js",
239
239
  "chunks": [
240
- "src-BLtNRhqm.js"
240
+ "src-Bv05c6Nj.js"
241
241
  ]
242
242
  }
243
243
  }
@@ -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.
@@ -41,6 +41,8 @@ const { thread, clonedMessages } = await memory.cloneThread({
41
41
 
42
42
  **options.messageLimit** (`number`): Maximum number of messages to clone. When set, clones the most recent N messages.
43
43
 
44
+ **options.contextWindowOnly** (`boolean`): Clone only the messages still in the context window. With Observational Memory configured and a source thread it has observed, that is the messages after lastObservedAt. Can't be combined with messageLimit or messageFilter.
45
+
44
46
  **options.messageFilter** (`MessageFilter`): Filter criteria for selecting which messages to clone.
45
47
 
46
48
  **options.messageFilter.startDate** (`Date`): Only clone messages created on or after this date.
@@ -174,4 +176,19 @@ When [Observational Memory](https://mastra.ai/docs/memory/observational-memory)
174
176
  - **Resource-scoped OM (deprecated, same `resourceId`)**: The OM record is shared between the source and cloned threads since they belong to the same resource. No duplication occurs.
175
177
  - **Resource-scoped OM (deprecated, different `resourceId`)**: The OM record is cloned to the new resource. Message IDs are remapped and any thread-identifying tags within observations are updated to reference the cloned thread.
176
178
 
177
- Only the current (most recent) OM generation is cloned. Older history generations aren't copied. Transient processing state (observation/reflection in-progress flags) is reset on the cloned record.
179
+ Only the current (most recent) OM generation is cloned. Older history generations aren't copied. Transient processing state (observation/reflection in-progress flags) is reset on the cloned record.
180
+
181
+ ### Copying only the context window
182
+
183
+ By default `cloneThread()` copies every message. Pass `contextWindowOnly: true` to copy only the messages in the context window. When OM is configured on the `Memory` instance and the source thread has observations, those are the messages created after `lastObservedAt` on the OM record the configured scope reads. The observations already carry the earlier messages. The source thread keeps all of its messages. When records exist for both scopes, the clone carries the one the configured scope reads.
184
+
185
+ With thread-scoped OM, the clone starts with the same context as the source: the same observations and the same unobserved messages. With resource-scoped OM cloned within the same resource, the clone shares the source's OM record, and the copied messages sit beside the originals in the resource. The resource's context can then hold both copies of each unobserved message. A resource-scoped clone into another resource doesn't carry the unobserved messages of the source resource's other threads.
186
+
187
+ The clone's stored message history holds only the copied messages, and thread-scoped semantic recall searches only those. Semantic recall with resource scope, the default, searches every thread of the resource. In a clone within the same resource it can still return the source's earlier messages. Without OM configured, or when OM hasn't observed anything yet, every message is still copied.
188
+
189
+ ```typescript
190
+ const { thread } = await memory.cloneThread({
191
+ sourceThreadId: 'thread-123',
192
+ options: { contextWindowOnly: true },
193
+ })
194
+ ```
@@ -41,6 +41,8 @@ const { thread, messageIdMap } = await memory.copyThread({
41
41
 
42
42
  **options.messageLimit** (`number`): Maximum number of messages to copy. When set, copies the most recent N messages.
43
43
 
44
+ **options.contextWindowOnly** (`boolean`): Copy only the messages still in the context window. With Observational Memory configured and a source thread it has observed, that is the messages after lastObservedAt. Can't be combined with messageLimit or messageFilter.
45
+
44
46
  **options.messageFilter** (`MessageFilter`): Filter criteria for selecting which messages to copy, by date range or message IDs.
45
47
 
46
48
  ## Returns
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_src = require("./src-fOZd9ewi.cjs");
2
+ const require_src = require("./src-D2dL-xVG.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.d.ts CHANGED
@@ -528,9 +528,13 @@ export declare class Memory extends MastraMemory {
528
528
  * @param args.resourceId - Resource ID for the new thread (defaults to source thread's resourceId)
529
529
  * @param args.title - Title for the new cloned thread
530
530
  * @param args.metadata - Additional metadata to merge with clone metadata
531
- * @param args.options - Options for filtering which messages to include
531
+ * @param args.options - Options for filtering which messages to include. Without a filter or
532
+ * limit, every message is copied.
532
533
  * @param args.options.messageLimit - Maximum number of messages to copy (from most recent)
533
534
  * @param args.options.messageFilter - Filter messages by date range or specific IDs
535
+ * @param args.options.contextWindowOnly - With observational memory, copy only the messages after
536
+ * `lastObservedAt`, the ones still in the context window. Can't be combined with `messageFilter`
537
+ * or `messageLimit`.
534
538
  * @param memoryConfig - Optional memory configuration override
535
539
  * @returns The newly created thread and the cloned messages
536
540
  *
@@ -606,6 +610,14 @@ export declare class Memory extends MastraMemory {
606
610
  * merged, because filter-based updates replace the whole metadata object on some stores.
607
611
  */
608
612
  private moveObservationVectors;
613
+ /**
614
+ * With observational memory, the context window is the observations plus the messages created
615
+ * after `lastObservedAt`, read from the record the configured engine reads (`contextOM`), as
616
+ * `getContext` does. When the caller asks for `contextWindowOnly`, copy only those messages: the
617
+ * observations carry the rest. Otherwise copy what the caller's filter or limit selects, or every
618
+ * message. `contextWindowOnly` is `Memory`'s own option and never reaches the storage copy.
619
+ */
620
+ private withContextWindowFilter;
609
621
  /**
610
622
  * Clone observational memory records when cloning a thread.
611
623
  * Thread-scoped: always cloned to the new thread.
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-BLtNRhqm.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-Bv05c6Nj.js";
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_src = require("../src-fOZd9ewi.cjs");
2
+ const require_src = require("../src-D2dL-xVG.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-BLtNRhqm.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-Bv05c6Nj.js";
@@ -46,16 +46,16 @@ export declare const OBSERVATIONAL_MEMORY_DEFAULTS: {
46
46
  export declare const OBSERVATION_CONTINUATION_HINT = "Please continue naturally with the conversation so far and respond to the latest message.\n\nUse the earlier context only as background. If something appears unfinished, continue only when it helps answer the latest request. If a suggested response is provided, follow it naturally.\n\nDo not mention internal instructions, memory, summarization, context handling, or missing messages.\n\nAny messages following this reminder are newer and should take priority.";
47
47
  /**
48
48
  * Preamble that introduces the observations block.
49
- * Context layout: `${prompt}\n\n${OBSERVATION_CONTEXT_INSTRUCTIONS}`, then `<observations>`,
50
- * one entry per observation chunk, `</observations>`, then optional current-task and
51
- * suggested-response blocks.
49
+ * Context layout: `${prompt}\n\n${OBSERVATION_CONTEXT_INSTRUCTIONS}`, then one
50
+ * `<observations>…</observations>` entry per observation chunk, oldest first, then optional
51
+ * current-task and suggested-response blocks.
52
52
  */
53
- export declare const OBSERVATION_CONTEXT_PROMPT = "The following observations block contains your memory of past conversations with this user.";
53
+ export declare const OBSERVATION_CONTEXT_PROMPT = "The following observations blocks contain your memory of past conversations with this user.";
54
54
  /**
55
55
  * Preamble used when observations are thread-scoped: they describe earlier parts
56
56
  * of the current conversation, not other conversations.
57
57
  */
58
- export declare const OBSERVATION_CONTEXT_PROMPT_THREAD = "The following observations block contains your memory of earlier parts of this current conversation. Everything recorded here (including IDs, artifacts, and tool results) came from this conversation and is available for you to reuse.";
58
+ export declare const OBSERVATION_CONTEXT_PROMPT_THREAD = "The following observations blocks contain your memory of earlier parts of this current conversation. Everything recorded here (including IDs, artifacts, and tool results) came from this conversation and is available for you to reuse.";
59
59
  /**
60
60
  * Returns the observations preamble matching the memory scope.
61
61
  * - `'thread'`: observations are earlier parts of the current conversation.
@@ -64,7 +64,7 @@ export declare const OBSERVATION_CONTEXT_PROMPT_THREAD = "The following observat
64
64
  export declare function getObservationContextPrompt(scope?: 'thread' | 'resource'): string;
65
65
  /**
66
66
  * Instructions that tell the model how to interpret and use observations.
67
- * Placed with the observations preamble, before the `<observations>` block.
67
+ * Placed with the observations preamble, before the `<observations>` blocks.
68
68
  */
69
69
  export declare const OBSERVATION_CONTEXT_INSTRUCTIONS = "IMPORTANT: When responding, reference specific details from these observations. Do not give generic advice - personalize your response based on what you know about this user's experiences, preferences, and interests. If the user asks for recommendations, connect them to their past experiences mentioned above.\n\nKNOWLEDGE UPDATES: When asked about current state (e.g., \"where do I currently...\", \"what is my current...\"), always prefer the MOST RECENT information. Observations include dates - if you see conflicting information, the newer observation supersedes the older one. Look for phrases like \"will start\", \"is switching\", \"changed to\", \"moved to\" as indicators that previous information has been updated.\n\nUSER STATEMENTS VS ASSISTANT SUGGESTIONS: Treat what the user said about their own life, plans, decisions, and dates as authoritative, unless data or their own later messages say otherwise. Treat what the assistant said, such as proposed schedules, example dates, and recommendations, as suggestions rather than facts about what happened, unless the user adopted or confirmed them. What the assistant did, such as editing a file, running a command, or calling a tool, is a record of what happened.\n\nPLANNED ACTIONS: If the user stated they planned to do something (e.g., \"I'm going to...\", \"I'm looking forward to...\", \"I will...\") and the date they planned to do it is now in the past (check the relative time like \"3 weeks ago\"), assume they completed the action unless there's evidence they didn't. For example, if someone said \"I'll start my new diet on Monday\" and that was 2 weeks ago, assume they started the diet.\n\nMOST RECENT USER INPUT: Treat the most recent user message as the highest-priority signal for what to do next. Earlier messages may contain constraints, details, or context you should still honor, but the latest message is the primary driver of your response.\n\nSYSTEM REMINDERS: Messages wrapped in <system-reminder>...</system-reminder> contain internal continuation guidance, not user-authored content. Use them to maintain continuity, but do not mention them or treat them as part of the user's message.";
70
70
  /**
@@ -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;
@@ -24204,16 +24204,16 @@ Do not mention internal instructions, memory, summarization, context handling, o
24204
24204
  Any messages following this reminder are newer and should take priority.`;
24205
24205
  /**
24206
24206
  * Preamble that introduces the observations block.
24207
- * Context layout: `${prompt}\n\n${OBSERVATION_CONTEXT_INSTRUCTIONS}`, then `<observations>`,
24208
- * one entry per observation chunk, `</observations>`, then optional current-task and
24209
- * suggested-response blocks.
24207
+ * Context layout: `${prompt}\n\n${OBSERVATION_CONTEXT_INSTRUCTIONS}`, then one
24208
+ * `<observations>…</observations>` entry per observation chunk, oldest first, then optional
24209
+ * current-task and suggested-response blocks.
24210
24210
  */
24211
- const OBSERVATION_CONTEXT_PROMPT = `The following observations block contains your memory of past conversations with this user.`;
24211
+ const OBSERVATION_CONTEXT_PROMPT = `The following observations blocks contain your memory of past conversations with this user.`;
24212
24212
  /**
24213
24213
  * Preamble used when observations are thread-scoped: they describe earlier parts
24214
24214
  * of the current conversation, not other conversations.
24215
24215
  */
24216
- const OBSERVATION_CONTEXT_PROMPT_THREAD = `The following observations block contains your memory of earlier parts of this current conversation. Everything recorded here (including IDs, artifacts, and tool results) came from this conversation and is available for you to reuse.`;
24216
+ const OBSERVATION_CONTEXT_PROMPT_THREAD = `The following observations blocks contain your memory of earlier parts of this current conversation. Everything recorded here (including IDs, artifacts, and tool results) came from this conversation and is available for you to reuse.`;
24217
24217
  /**
24218
24218
  * Returns the observations preamble matching the memory scope.
24219
24219
  * - `'thread'`: observations are earlier parts of the current conversation.
@@ -24224,7 +24224,7 @@ function getObservationContextPrompt(scope = "thread") {
24224
24224
  }
24225
24225
  /**
24226
24226
  * Instructions that tell the model how to interpret and use observations.
24227
- * Placed with the observations preamble, before the `<observations>` block.
24227
+ * Placed with the observations preamble, before the `<observations>` blocks.
24228
24228
  */
24229
24229
  const OBSERVATION_CONTEXT_INSTRUCTIONS = `IMPORTANT: When responding, reference specific details from these observations. Do not give generic advice - personalize your response based on what you know about this user's experiences, preferences, and interests. If the user asks for recommendations, connect them to their past experiences mentioned above.
24230
24230
 
@@ -36013,6 +36013,7 @@ var ObservationTurn = class {
36013
36013
  responseMessageId;
36014
36014
  /** Processor-provided hooks for turn/step lifecycle integration. */
36015
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. */
36016
36017
  abortSignal;
36017
36018
  constructor(opts) {
36018
36019
  this.abortSignal = opts.abortSignal;
@@ -38986,8 +38987,7 @@ var ObservationalMemory = class ObservationalMemory {
38986
38987
  if (currentDate) optimized = addRelativeTimeToObservations(optimized, currentDate, timeZone);
38987
38988
  const messages = [`${getObservationContextPrompt(this.scope)}\n\n${OBSERVATION_CONTEXT_INSTRUCTIONS}${retrieval ? `\n\n${getRetrievalInstructions(this.retrievalScope, this.retrievalInstructions, this.retrievalSearch, this.storage.supportsObservationalMemoryHistorySearch === true)}` : ""}`];
38988
38989
  if (unobservedContextBlocks) messages.push(`The following content is from OTHER conversations different from the current conversation, they're here for reference, but they're not necessarily your focus:\nSTART_OTHER_CONVERSATIONS_BLOCK\n${unobservedContextBlocks}\nEND_OTHER_CONVERSATIONS_BLOCK`);
38989
- const observationChunks = this.splitObservationContextChunks(optimized);
38990
- if (observationChunks.length > 0) messages.push("<observations>", ...observationChunks, "</observations>");
38990
+ for (const chunk of this.splitObservationContextChunks(optimized)) messages.push(`<observations>\n${chunk}\n</observations>`);
38991
38991
  if (currentTask) messages.push(`<current-task>\n${currentTask}\n</current-task>`);
38992
38992
  if (suggestedResponse) messages.push(`<suggested-response>\n${suggestedResponse}\n</suggested-response>`);
38993
38993
  messages.push(...buildExtractedValueContextSections([...this.observationConfig.extractors, ...this.reflectionConfig.extractors], extractedValues));
@@ -39415,6 +39415,16 @@ ${formattedMessages}
39415
39415
  let skipped = 0;
39416
39416
  let backoffTriggered = false;
39417
39417
  const retentionCounter = typeof retentionFloor === "number" ? new TokenCounter() : null;
39418
+ const tokensById = /* @__PURE__ */ new Map();
39419
+ let remainingTokens = 0;
39420
+ let remainingIds = 0;
39421
+ if (retentionCounter) {
39422
+ const countable = messages.filter((m) => m?.id && m.id !== "om-continuation");
39423
+ remainingTokens = retentionCounter.countMessages(countable);
39424
+ for (const m of countable) tokensById.set(m.id, (tokensById.get(m.id) ?? 0) + retentionCounter.countMessage(m));
39425
+ remainingIds = tokensById.size;
39426
+ }
39427
+ const remainingCount = (tokens, ids) => ids === 0 ? 0 : tokens;
39418
39428
  for (const msg of messages) {
39419
39429
  if (!msg?.id || msg.id === "om-continuation" || !observedSet.has(msg.id)) continue;
39420
39430
  if (preserveSet?.has(msg.id)) {
@@ -39424,31 +39434,40 @@ ${formattedMessages}
39424
39434
  const unobservedParts = getUnobservedParts(msg);
39425
39435
  const totalParts = msg.content?.parts?.length ?? 0;
39426
39436
  if (unobservedParts.length > 0 && unobservedParts.length < totalParts) {
39437
+ const tokensBefore = retentionCounter ? retentionCounter.countMessage(msg) : 0;
39427
39438
  msg.content.parts = unobservedParts;
39439
+ if (retentionCounter) {
39440
+ const delta = retentionCounter.countMessage(msg) - tokensBefore;
39441
+ tokensById.set(msg.id, (tokensById.get(msg.id) ?? 0) + delta);
39442
+ if (!idsToRemove.has(msg.id)) remainingTokens += delta;
39443
+ }
39428
39444
  continue;
39429
39445
  }
39446
+ const alreadyRemoved = idsToRemove.has(msg.id);
39447
+ const msgTokens = tokensById.get(msg.id) ?? 0;
39430
39448
  if (retentionCounter && typeof retentionFloor === "number") {
39431
- const nextRemainingMessages = messages.filter((m) => m?.id && m.id !== "om-continuation" && !idsToRemove.has(m.id) && m.id !== msg.id);
39432
- if (retentionCounter.countMessages(nextRemainingMessages) < retentionFloor) {
39449
+ const idsIfRemoved = alreadyRemoved ? remainingIds : remainingIds - 1;
39450
+ if (remainingCount(alreadyRemoved ? remainingTokens : remainingTokens - msgTokens, idsIfRemoved) < retentionFloor) {
39433
39451
  skipped += 1;
39434
39452
  backoffTriggered = true;
39435
39453
  break;
39436
39454
  }
39437
39455
  }
39456
+ if (!alreadyRemoved) {
39457
+ remainingTokens -= msgTokens;
39458
+ remainingIds -= 1;
39459
+ }
39438
39460
  idsToRemove.add(msg.id);
39439
39461
  removalOrder.push(msg.id);
39440
39462
  }
39441
- if (retentionCounter && typeof retentionFloor === "number" && idsToRemove.size > 0) {
39442
- let remainingMessages = messages.filter((m) => m?.id && m.id !== "om-continuation" && !idsToRemove.has(m.id));
39443
- let remainingTokens = retentionCounter.countMessages(remainingMessages);
39444
- while (remainingTokens < retentionFloor && removalOrder.length > 0) {
39445
- const restoreId = removalOrder.pop();
39446
- idsToRemove.delete(restoreId);
39447
- skipped += 1;
39448
- backoffTriggered = true;
39449
- remainingMessages = messages.filter((m) => m?.id && m.id !== "om-continuation" && !idsToRemove.has(m.id));
39450
- remainingTokens = retentionCounter.countMessages(remainingMessages);
39463
+ if (retentionCounter && typeof retentionFloor === "number" && idsToRemove.size > 0) while (remainingCount(remainingTokens, remainingIds) < retentionFloor && removalOrder.length > 0) {
39464
+ const restoreId = removalOrder.pop();
39465
+ if (idsToRemove.delete(restoreId)) {
39466
+ remainingTokens += tokensById.get(restoreId) ?? 0;
39467
+ remainingIds += 1;
39451
39468
  }
39469
+ skipped += 1;
39470
+ backoffTriggered = true;
39452
39471
  }
39453
39472
  omDebug(`[OM:cleanupActivation] matched=${idsToRemove.size}, skipped=${skipped}, backoffTriggered=${backoffTriggered}`);
39454
39473
  return [...idsToRemove];
@@ -41060,6 +41079,7 @@ var ObservationalMemoryProcessor = class {
41060
41079
  const observabilityContext = getOmObservabilityContext(args);
41061
41080
  state.__omObservabilityContext = observabilityContext;
41062
41081
  this.turn.observabilityContext = observabilityContext;
41082
+ this.turn.abortSignal = abortSignal;
41063
41083
  this.turn.actorModelContext = actorModelContext;
41064
41084
  this.turn.responseMessageId = responseMessageId;
41065
41085
  {
@@ -43248,9 +43268,13 @@ Notes:
43248
43268
  * @param args.resourceId - Resource ID for the new thread (defaults to source thread's resourceId)
43249
43269
  * @param args.title - Title for the new cloned thread
43250
43270
  * @param args.metadata - Additional metadata to merge with clone metadata
43251
- * @param args.options - Options for filtering which messages to include
43271
+ * @param args.options - Options for filtering which messages to include. Without a filter or
43272
+ * limit, every message is copied.
43252
43273
  * @param args.options.messageLimit - Maximum number of messages to copy (from most recent)
43253
43274
  * @param args.options.messageFilter - Filter messages by date range or specific IDs
43275
+ * @param args.options.contextWindowOnly - With observational memory, copy only the messages after
43276
+ * `lastObservedAt`, the ones still in the context window. Can't be combined with `messageFilter`
43277
+ * or `messageLimit`.
43254
43278
  * @param memoryConfig - Optional memory configuration override
43255
43279
  * @returns The newly created thread and the cloned messages
43256
43280
  *
@@ -43320,8 +43344,11 @@ Notes:
43320
43344
  async copyThread(args, memoryConfig) {
43321
43345
  const memoryStore = await this.getMemoryStore();
43322
43346
  const config = this.getMergedThreadConfig(memoryConfig);
43323
- const result = await memoryStore.copyThread(args);
43324
43347
  const sourceResourceId = (await this.getThreadById({ threadId: args.sourceThreadId }))?.resourceId;
43348
+ const omEngine = await this.omEngine;
43349
+ const liveContextOM = omEngine && sourceResourceId ? await omEngine.getRecord(args.sourceThreadId, sourceResourceId) : null;
43350
+ const contextOM = liveContextOM ? structuredClone(liveContextOM) : null;
43351
+ const result = await memoryStore.copyThread(this.withContextWindowFilter(args, contextOM));
43325
43352
  let priorDestinationResourceWm;
43326
43353
  if (config.workingMemory?.enabled) {
43327
43354
  const scope = config.workingMemory.scope || "resource";
@@ -43343,7 +43370,7 @@ Notes:
43343
43370
  }
43344
43371
  }
43345
43372
  if (memoryStore.supportsObservationalMemory && sourceResourceId) try {
43346
- await this.cloneObservationalMemory(memoryStore, args.sourceThreadId, sourceResourceId, result);
43373
+ await this.cloneObservationalMemory(memoryStore, args.sourceThreadId, sourceResourceId, result, contextOM);
43347
43374
  } catch (error) {
43348
43375
  await this.rollbackCopiedThread(memoryStore, result.thread, "OM clone", false, priorDestinationResourceWm);
43349
43376
  throw error;
@@ -43536,13 +43563,38 @@ Notes:
43536
43563
  }
43537
43564
  }
43538
43565
  /**
43566
+ * With observational memory, the context window is the observations plus the messages created
43567
+ * after `lastObservedAt`, read from the record the configured engine reads (`contextOM`), as
43568
+ * `getContext` does. When the caller asks for `contextWindowOnly`, copy only those messages: the
43569
+ * observations carry the rest. Otherwise copy what the caller's filter or limit selects, or every
43570
+ * message. `contextWindowOnly` is `Memory`'s own option and never reaches the storage copy.
43571
+ */
43572
+ withContextWindowFilter(args, contextOM) {
43573
+ const { contextWindowOnly, ...options } = args.options ?? {};
43574
+ if (contextWindowOnly && (options.messageFilter !== void 0 || options.messageLimit !== void 0)) throw new Error("cloneThread: contextWindowOnly copies only the messages in the context window and cannot be combined with messageFilter or messageLimit");
43575
+ const storageArgs = args.options ? {
43576
+ ...args,
43577
+ options
43578
+ } : args;
43579
+ if (!contextWindowOnly || !contextOM?.lastObservedAt) return storageArgs;
43580
+ const startDate = new Date(new Date(contextOM.lastObservedAt).getTime() + 1);
43581
+ return {
43582
+ ...storageArgs,
43583
+ options: {
43584
+ ...options,
43585
+ messageFilter: { startDate }
43586
+ }
43587
+ };
43588
+ }
43589
+ /**
43539
43590
  * Clone observational memory records when cloning a thread.
43540
43591
  * Thread-scoped: always cloned to the new thread.
43541
43592
  * Resource-scoped: cloned only when the resourceId changes (same resourceId shares OM naturally).
43542
43593
  * All stored message/thread IDs are remapped to the cloned IDs.
43543
43594
  */
43544
- async cloneObservationalMemory(memoryStore, sourceThreadId, sourceResourceId, result) {
43545
- let sourceOM = await memoryStore.getObservationalMemory(sourceThreadId, sourceResourceId);
43595
+ async cloneObservationalMemory(memoryStore, sourceThreadId, sourceResourceId, result, contextOM) {
43596
+ let sourceOM = contextOM;
43597
+ if (!sourceOM) sourceOM = await memoryStore.getObservationalMemory(sourceThreadId, sourceResourceId);
43546
43598
  if (!sourceOM) sourceOM = await memoryStore.getObservationalMemory(null, sourceResourceId);
43547
43599
  if (!sourceOM) return;
43548
43600
  const clonedThreadId = result.thread.id;
@@ -24226,16 +24226,16 @@ Do not mention internal instructions, memory, summarization, context handling, o
24226
24226
  Any messages following this reminder are newer and should take priority.`;
24227
24227
  /**
24228
24228
  * Preamble that introduces the observations block.
24229
- * Context layout: `${prompt}\n\n${OBSERVATION_CONTEXT_INSTRUCTIONS}`, then `<observations>`,
24230
- * one entry per observation chunk, `</observations>`, then optional current-task and
24231
- * suggested-response blocks.
24229
+ * Context layout: `${prompt}\n\n${OBSERVATION_CONTEXT_INSTRUCTIONS}`, then one
24230
+ * `<observations>…</observations>` entry per observation chunk, oldest first, then optional
24231
+ * current-task and suggested-response blocks.
24232
24232
  */
24233
- const OBSERVATION_CONTEXT_PROMPT = `The following observations block contains your memory of past conversations with this user.`;
24233
+ const OBSERVATION_CONTEXT_PROMPT = `The following observations blocks contain your memory of past conversations with this user.`;
24234
24234
  /**
24235
24235
  * Preamble used when observations are thread-scoped: they describe earlier parts
24236
24236
  * of the current conversation, not other conversations.
24237
24237
  */
24238
- const OBSERVATION_CONTEXT_PROMPT_THREAD = `The following observations block contains your memory of earlier parts of this current conversation. Everything recorded here (including IDs, artifacts, and tool results) came from this conversation and is available for you to reuse.`;
24238
+ const OBSERVATION_CONTEXT_PROMPT_THREAD = `The following observations blocks contain your memory of earlier parts of this current conversation. Everything recorded here (including IDs, artifacts, and tool results) came from this conversation and is available for you to reuse.`;
24239
24239
  /**
24240
24240
  * Returns the observations preamble matching the memory scope.
24241
24241
  * - `'thread'`: observations are earlier parts of the current conversation.
@@ -24246,7 +24246,7 @@ function getObservationContextPrompt(scope = "thread") {
24246
24246
  }
24247
24247
  /**
24248
24248
  * Instructions that tell the model how to interpret and use observations.
24249
- * Placed with the observations preamble, before the `<observations>` block.
24249
+ * Placed with the observations preamble, before the `<observations>` blocks.
24250
24250
  */
24251
24251
  const OBSERVATION_CONTEXT_INSTRUCTIONS = `IMPORTANT: When responding, reference specific details from these observations. Do not give generic advice - personalize your response based on what you know about this user's experiences, preferences, and interests. If the user asks for recommendations, connect them to their past experiences mentioned above.
24252
24252
 
@@ -36035,6 +36035,7 @@ var ObservationTurn = class {
36035
36035
  responseMessageId;
36036
36036
  /** Processor-provided hooks for turn/step lifecycle integration. */
36037
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. */
36038
36039
  abortSignal;
36039
36040
  constructor(opts) {
36040
36041
  this.abortSignal = opts.abortSignal;
@@ -39008,8 +39009,7 @@ var ObservationalMemory = class ObservationalMemory {
39008
39009
  if (currentDate) optimized = addRelativeTimeToObservations(optimized, currentDate, timeZone);
39009
39010
  const messages = [`${getObservationContextPrompt(this.scope)}\n\n${OBSERVATION_CONTEXT_INSTRUCTIONS}${retrieval ? `\n\n${getRetrievalInstructions(this.retrievalScope, this.retrievalInstructions, this.retrievalSearch, this.storage.supportsObservationalMemoryHistorySearch === true)}` : ""}`];
39010
39011
  if (unobservedContextBlocks) messages.push(`The following content is from OTHER conversations different from the current conversation, they're here for reference, but they're not necessarily your focus:\nSTART_OTHER_CONVERSATIONS_BLOCK\n${unobservedContextBlocks}\nEND_OTHER_CONVERSATIONS_BLOCK`);
39011
- const observationChunks = this.splitObservationContextChunks(optimized);
39012
- if (observationChunks.length > 0) messages.push("<observations>", ...observationChunks, "</observations>");
39012
+ for (const chunk of this.splitObservationContextChunks(optimized)) messages.push(`<observations>\n${chunk}\n</observations>`);
39013
39013
  if (currentTask) messages.push(`<current-task>\n${currentTask}\n</current-task>`);
39014
39014
  if (suggestedResponse) messages.push(`<suggested-response>\n${suggestedResponse}\n</suggested-response>`);
39015
39015
  messages.push(...buildExtractedValueContextSections([...this.observationConfig.extractors, ...this.reflectionConfig.extractors], extractedValues));
@@ -39437,6 +39437,16 @@ ${formattedMessages}
39437
39437
  let skipped = 0;
39438
39438
  let backoffTriggered = false;
39439
39439
  const retentionCounter = typeof retentionFloor === "number" ? new TokenCounter() : null;
39440
+ const tokensById = /* @__PURE__ */ new Map();
39441
+ let remainingTokens = 0;
39442
+ let remainingIds = 0;
39443
+ if (retentionCounter) {
39444
+ const countable = messages.filter((m) => m?.id && m.id !== "om-continuation");
39445
+ remainingTokens = retentionCounter.countMessages(countable);
39446
+ for (const m of countable) tokensById.set(m.id, (tokensById.get(m.id) ?? 0) + retentionCounter.countMessage(m));
39447
+ remainingIds = tokensById.size;
39448
+ }
39449
+ const remainingCount = (tokens, ids) => ids === 0 ? 0 : tokens;
39440
39450
  for (const msg of messages) {
39441
39451
  if (!msg?.id || msg.id === "om-continuation" || !observedSet.has(msg.id)) continue;
39442
39452
  if (preserveSet?.has(msg.id)) {
@@ -39446,31 +39456,40 @@ ${formattedMessages}
39446
39456
  const unobservedParts = getUnobservedParts(msg);
39447
39457
  const totalParts = msg.content?.parts?.length ?? 0;
39448
39458
  if (unobservedParts.length > 0 && unobservedParts.length < totalParts) {
39459
+ const tokensBefore = retentionCounter ? retentionCounter.countMessage(msg) : 0;
39449
39460
  msg.content.parts = unobservedParts;
39461
+ if (retentionCounter) {
39462
+ const delta = retentionCounter.countMessage(msg) - tokensBefore;
39463
+ tokensById.set(msg.id, (tokensById.get(msg.id) ?? 0) + delta);
39464
+ if (!idsToRemove.has(msg.id)) remainingTokens += delta;
39465
+ }
39450
39466
  continue;
39451
39467
  }
39468
+ const alreadyRemoved = idsToRemove.has(msg.id);
39469
+ const msgTokens = tokensById.get(msg.id) ?? 0;
39452
39470
  if (retentionCounter && typeof retentionFloor === "number") {
39453
- const nextRemainingMessages = messages.filter((m) => m?.id && m.id !== "om-continuation" && !idsToRemove.has(m.id) && m.id !== msg.id);
39454
- if (retentionCounter.countMessages(nextRemainingMessages) < retentionFloor) {
39471
+ const idsIfRemoved = alreadyRemoved ? remainingIds : remainingIds - 1;
39472
+ if (remainingCount(alreadyRemoved ? remainingTokens : remainingTokens - msgTokens, idsIfRemoved) < retentionFloor) {
39455
39473
  skipped += 1;
39456
39474
  backoffTriggered = true;
39457
39475
  break;
39458
39476
  }
39459
39477
  }
39478
+ if (!alreadyRemoved) {
39479
+ remainingTokens -= msgTokens;
39480
+ remainingIds -= 1;
39481
+ }
39460
39482
  idsToRemove.add(msg.id);
39461
39483
  removalOrder.push(msg.id);
39462
39484
  }
39463
- if (retentionCounter && typeof retentionFloor === "number" && idsToRemove.size > 0) {
39464
- let remainingMessages = messages.filter((m) => m?.id && m.id !== "om-continuation" && !idsToRemove.has(m.id));
39465
- let remainingTokens = retentionCounter.countMessages(remainingMessages);
39466
- while (remainingTokens < retentionFloor && removalOrder.length > 0) {
39467
- const restoreId = removalOrder.pop();
39468
- idsToRemove.delete(restoreId);
39469
- skipped += 1;
39470
- backoffTriggered = true;
39471
- remainingMessages = messages.filter((m) => m?.id && m.id !== "om-continuation" && !idsToRemove.has(m.id));
39472
- remainingTokens = retentionCounter.countMessages(remainingMessages);
39485
+ if (retentionCounter && typeof retentionFloor === "number" && idsToRemove.size > 0) while (remainingCount(remainingTokens, remainingIds) < retentionFloor && removalOrder.length > 0) {
39486
+ const restoreId = removalOrder.pop();
39487
+ if (idsToRemove.delete(restoreId)) {
39488
+ remainingTokens += tokensById.get(restoreId) ?? 0;
39489
+ remainingIds += 1;
39473
39490
  }
39491
+ skipped += 1;
39492
+ backoffTriggered = true;
39474
39493
  }
39475
39494
  omDebug(`[OM:cleanupActivation] matched=${idsToRemove.size}, skipped=${skipped}, backoffTriggered=${backoffTriggered}`);
39476
39495
  return [...idsToRemove];
@@ -41082,6 +41101,7 @@ var ObservationalMemoryProcessor = class {
41082
41101
  const observabilityContext = getOmObservabilityContext(args);
41083
41102
  state.__omObservabilityContext = observabilityContext;
41084
41103
  this.turn.observabilityContext = observabilityContext;
41104
+ this.turn.abortSignal = abortSignal;
41085
41105
  this.turn.actorModelContext = actorModelContext;
41086
41106
  this.turn.responseMessageId = responseMessageId;
41087
41107
  {
@@ -43270,9 +43290,13 @@ Notes:
43270
43290
  * @param args.resourceId - Resource ID for the new thread (defaults to source thread's resourceId)
43271
43291
  * @param args.title - Title for the new cloned thread
43272
43292
  * @param args.metadata - Additional metadata to merge with clone metadata
43273
- * @param args.options - Options for filtering which messages to include
43293
+ * @param args.options - Options for filtering which messages to include. Without a filter or
43294
+ * limit, every message is copied.
43274
43295
  * @param args.options.messageLimit - Maximum number of messages to copy (from most recent)
43275
43296
  * @param args.options.messageFilter - Filter messages by date range or specific IDs
43297
+ * @param args.options.contextWindowOnly - With observational memory, copy only the messages after
43298
+ * `lastObservedAt`, the ones still in the context window. Can't be combined with `messageFilter`
43299
+ * or `messageLimit`.
43276
43300
  * @param memoryConfig - Optional memory configuration override
43277
43301
  * @returns The newly created thread and the cloned messages
43278
43302
  *
@@ -43342,8 +43366,11 @@ Notes:
43342
43366
  async copyThread(args, memoryConfig) {
43343
43367
  const memoryStore = await this.getMemoryStore();
43344
43368
  const config = this.getMergedThreadConfig(memoryConfig);
43345
- const result = await memoryStore.copyThread(args);
43346
43369
  const sourceResourceId = (await this.getThreadById({ threadId: args.sourceThreadId }))?.resourceId;
43370
+ const omEngine = await this.omEngine;
43371
+ const liveContextOM = omEngine && sourceResourceId ? await omEngine.getRecord(args.sourceThreadId, sourceResourceId) : null;
43372
+ const contextOM = liveContextOM ? structuredClone(liveContextOM) : null;
43373
+ const result = await memoryStore.copyThread(this.withContextWindowFilter(args, contextOM));
43347
43374
  let priorDestinationResourceWm;
43348
43375
  if (config.workingMemory?.enabled) {
43349
43376
  const scope = config.workingMemory.scope || "resource";
@@ -43365,7 +43392,7 @@ Notes:
43365
43392
  }
43366
43393
  }
43367
43394
  if (memoryStore.supportsObservationalMemory && sourceResourceId) try {
43368
- await this.cloneObservationalMemory(memoryStore, args.sourceThreadId, sourceResourceId, result);
43395
+ await this.cloneObservationalMemory(memoryStore, args.sourceThreadId, sourceResourceId, result, contextOM);
43369
43396
  } catch (error) {
43370
43397
  await this.rollbackCopiedThread(memoryStore, result.thread, "OM clone", false, priorDestinationResourceWm);
43371
43398
  throw error;
@@ -43558,13 +43585,38 @@ Notes:
43558
43585
  }
43559
43586
  }
43560
43587
  /**
43588
+ * With observational memory, the context window is the observations plus the messages created
43589
+ * after `lastObservedAt`, read from the record the configured engine reads (`contextOM`), as
43590
+ * `getContext` does. When the caller asks for `contextWindowOnly`, copy only those messages: the
43591
+ * observations carry the rest. Otherwise copy what the caller's filter or limit selects, or every
43592
+ * message. `contextWindowOnly` is `Memory`'s own option and never reaches the storage copy.
43593
+ */
43594
+ withContextWindowFilter(args, contextOM) {
43595
+ const { contextWindowOnly, ...options } = args.options ?? {};
43596
+ if (contextWindowOnly && (options.messageFilter !== void 0 || options.messageLimit !== void 0)) throw new Error("cloneThread: contextWindowOnly copies only the messages in the context window and cannot be combined with messageFilter or messageLimit");
43597
+ const storageArgs = args.options ? {
43598
+ ...args,
43599
+ options
43600
+ } : args;
43601
+ if (!contextWindowOnly || !contextOM?.lastObservedAt) return storageArgs;
43602
+ const startDate = new Date(new Date(contextOM.lastObservedAt).getTime() + 1);
43603
+ return {
43604
+ ...storageArgs,
43605
+ options: {
43606
+ ...options,
43607
+ messageFilter: { startDate }
43608
+ }
43609
+ };
43610
+ }
43611
+ /**
43561
43612
  * Clone observational memory records when cloning a thread.
43562
43613
  * Thread-scoped: always cloned to the new thread.
43563
43614
  * Resource-scoped: cloned only when the resourceId changes (same resourceId shares OM naturally).
43564
43615
  * All stored message/thread IDs are remapped to the cloned IDs.
43565
43616
  */
43566
- async cloneObservationalMemory(memoryStore, sourceThreadId, sourceResourceId, result) {
43567
- let sourceOM = await memoryStore.getObservationalMemory(sourceThreadId, sourceResourceId);
43617
+ async cloneObservationalMemory(memoryStore, sourceThreadId, sourceResourceId, result, contextOM) {
43618
+ let sourceOM = contextOM;
43619
+ if (!sourceOM) sourceOM = await memoryStore.getObservationalMemory(sourceThreadId, sourceResourceId);
43568
43620
  if (!sourceOM) sourceOM = await memoryStore.getObservationalMemory(null, sourceResourceId);
43569
43621
  if (!sourceOM) return;
43570
43622
  const clonedThreadId = result.thread.id;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/memory",
3
- "version": "1.41.4-alpha.0",
3
+ "version": "1.42.0-alpha.2",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -73,7 +73,7 @@
73
73
  "@internal/ai-v7": "0.0.99",
74
74
  "@internal/lint": "0.0.152",
75
75
  "@internal/types-builder": "0.0.127",
76
- "@mastra/core": "1.87.0-alpha.4"
76
+ "@mastra/core": "1.87.0-alpha.11"
77
77
  },
78
78
  "peerDependencies": {
79
79
  "@mastra/core": ">=1.85.1-0 <2.0.0-0"