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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/CHANGELOG.md +4656 -3
  2. package/LICENSE.md +15 -0
  3. package/README.md +26 -1
  4. package/dist/_types/@internal_ai-sdk-v4/dist/index.d.ts +7450 -0
  5. package/dist/docs/SKILL.md +62 -0
  6. package/dist/docs/assets/SOURCE_MAP.json +11 -0
  7. package/dist/docs/references/docs-agents-agent-approval.md +664 -0
  8. package/dist/docs/references/docs-agents-networks.md +184 -0
  9. package/dist/docs/references/docs-capabilities-subagents.md +454 -0
  10. package/dist/docs/references/docs-evals-evals-with-memory.md +146 -0
  11. package/dist/docs/references/docs-long-running-agents-background-tasks.md +382 -0
  12. package/dist/docs/references/docs-long-running-agents-goals.md +118 -0
  13. package/dist/docs/references/docs-memory-memory-processors.md +385 -0
  14. package/dist/docs/references/docs-memory-message-history.md +348 -0
  15. package/dist/docs/references/docs-memory-multi-user-threads.md +208 -0
  16. package/dist/docs/references/docs-memory-observational-memory.md +835 -0
  17. package/dist/docs/references/docs-memory-overview.md +266 -0
  18. package/dist/docs/references/docs-memory-semantic-recall.md +401 -0
  19. package/dist/docs/references/docs-memory-working-memory.md +431 -0
  20. package/dist/docs/references/docs-storage-overview.md +214 -0
  21. package/dist/docs/references/reference-core-getMemory.md +51 -0
  22. package/dist/docs/references/reference-core-listMemory.md +57 -0
  23. package/dist/docs/references/reference-file-based-agents-memory.md +58 -0
  24. package/dist/docs/references/reference-memory-clone-utilities.md +203 -0
  25. package/dist/docs/references/reference-memory-cloneThread.md +173 -0
  26. package/dist/docs/references/reference-memory-createThread.md +70 -0
  27. package/dist/docs/references/reference-memory-getThreadById.md +26 -0
  28. package/dist/docs/references/reference-memory-listThreads.md +147 -0
  29. package/dist/docs/references/reference-memory-memory-class.md +148 -0
  30. package/dist/docs/references/reference-memory-observational-memory.md +877 -0
  31. package/dist/docs/references/reference-memory-summarizeConversation.md +99 -0
  32. package/dist/docs/references/reference-memory-summarizeThread.md +93 -0
  33. package/dist/docs/references/reference-processors-token-limiter-processor.md +158 -0
  34. package/dist/docs/references/reference-storage-dsql.md +430 -0
  35. package/dist/docs/references/reference-storage-dynamodb.md +284 -0
  36. package/dist/docs/references/reference-storage-libsql.md +143 -0
  37. package/dist/docs/references/reference-storage-mongodb.md +267 -0
  38. package/dist/docs/references/reference-storage-postgresql.md +531 -0
  39. package/dist/docs/references/reference-storage-redis.md +268 -0
  40. package/dist/docs/references/reference-storage-upstash.md +162 -0
  41. package/dist/docs/references/reference-vectors-libsql.md +307 -0
  42. package/dist/docs/references/reference-vectors-mongodb.md +567 -0
  43. package/dist/docs/references/reference-vectors-pg.md +430 -0
  44. package/dist/docs/references/reference-vectors-upstash.md +296 -0
  45. package/dist/index.cjs +35 -893
  46. package/dist/index.d.ts +465 -62
  47. package/dist/index.d.ts.map +1 -1
  48. package/dist/index.js +2 -887
  49. package/dist/processors/index.cjs +32 -165
  50. package/dist/processors/index.d.ts +1 -2
  51. package/dist/processors/index.d.ts.map +1 -1
  52. package/dist/processors/index.js +2 -158
  53. package/dist/processors/observational-memory/activation-ttl.d.ts +4 -0
  54. package/dist/processors/observational-memory/activation-ttl.d.ts.map +1 -0
  55. package/dist/processors/observational-memory/anchor-ids.d.ts +4 -0
  56. package/dist/processors/observational-memory/anchor-ids.d.ts.map +1 -0
  57. package/dist/processors/observational-memory/buffering-coordinator.d.ts +61 -0
  58. package/dist/processors/observational-memory/buffering-coordinator.d.ts.map +1 -0
  59. package/dist/processors/observational-memory/built-in-extractors.d.ts +15 -0
  60. package/dist/processors/observational-memory/built-in-extractors.d.ts.map +1 -0
  61. package/dist/processors/observational-memory/constants.d.ts +74 -0
  62. package/dist/processors/observational-memory/constants.d.ts.map +1 -0
  63. package/dist/processors/observational-memory/date-utils.d.ts +41 -0
  64. package/dist/processors/observational-memory/date-utils.d.ts.map +1 -0
  65. package/dist/processors/observational-memory/debug.d.ts +3 -0
  66. package/dist/processors/observational-memory/debug.d.ts.map +1 -0
  67. package/dist/processors/observational-memory/extracted-values.d.ts +44 -0
  68. package/dist/processors/observational-memory/extracted-values.d.ts.map +1 -0
  69. package/dist/processors/observational-memory/extraction-runner.d.ts +22 -0
  70. package/dist/processors/observational-memory/extraction-runner.d.ts.map +1 -0
  71. package/dist/processors/observational-memory/extractor.d.ts +76 -0
  72. package/dist/processors/observational-memory/extractor.d.ts.map +1 -0
  73. package/dist/processors/observational-memory/index.d.ts +30 -0
  74. package/dist/processors/observational-memory/index.d.ts.map +1 -0
  75. package/dist/processors/observational-memory/internal-request-context.d.ts +17 -0
  76. package/dist/processors/observational-memory/internal-request-context.d.ts.map +1 -0
  77. package/dist/processors/observational-memory/markers.d.ts +118 -0
  78. package/dist/processors/observational-memory/markers.d.ts.map +1 -0
  79. package/dist/processors/observational-memory/message-utils.d.ts +83 -0
  80. package/dist/processors/observational-memory/message-utils.d.ts.map +1 -0
  81. package/dist/processors/observational-memory/model-by-input-tokens.d.ts +14 -0
  82. package/dist/processors/observational-memory/model-by-input-tokens.d.ts.map +1 -0
  83. package/dist/processors/observational-memory/model-context.d.ts +2 -0
  84. package/dist/processors/observational-memory/model-context.d.ts.map +1 -0
  85. package/dist/processors/observational-memory/observation-groups.d.ts +15 -0
  86. package/dist/processors/observational-memory/observation-groups.d.ts.map +1 -0
  87. package/dist/processors/observational-memory/observation-strategies/async-buffer.d.ts +39 -0
  88. package/dist/processors/observational-memory/observation-strategies/async-buffer.d.ts.map +1 -0
  89. package/dist/processors/observational-memory/observation-strategies/base.d.ts +122 -0
  90. package/dist/processors/observational-memory/observation-strategies/base.d.ts.map +1 -0
  91. package/dist/processors/observational-memory/observation-strategies/index.d.ts +7 -0
  92. package/dist/processors/observational-memory/observation-strategies/index.d.ts.map +1 -0
  93. package/dist/processors/observational-memory/observation-strategies/resource-scoped.d.ts +43 -0
  94. package/dist/processors/observational-memory/observation-strategies/resource-scoped.d.ts.map +1 -0
  95. package/dist/processors/observational-memory/observation-strategies/sync.d.ts +41 -0
  96. package/dist/processors/observational-memory/observation-strategies/sync.d.ts.map +1 -0
  97. package/dist/processors/observational-memory/observation-strategies/types.d.ts +103 -0
  98. package/dist/processors/observational-memory/observation-strategies/types.d.ts.map +1 -0
  99. package/dist/processors/observational-memory/observation-turn/index.d.ts +4 -0
  100. package/dist/processors/observational-memory/observation-turn/index.d.ts.map +1 -0
  101. package/dist/processors/observational-memory/observation-turn/load-memory-context.d.ts +9 -0
  102. package/dist/processors/observational-memory/observation-turn/load-memory-context.d.ts.map +1 -0
  103. package/dist/processors/observational-memory/observation-turn/step.d.ts +53 -0
  104. package/dist/processors/observational-memory/observation-turn/step.d.ts.map +1 -0
  105. package/dist/processors/observational-memory/observation-turn/turn.d.ts +139 -0
  106. package/dist/processors/observational-memory/observation-turn/turn.d.ts.map +1 -0
  107. package/dist/processors/observational-memory/observation-turn/types.d.ts +46 -0
  108. package/dist/processors/observational-memory/observation-turn/types.d.ts.map +1 -0
  109. package/dist/processors/observational-memory/observation-utils.d.ts +16 -0
  110. package/dist/processors/observational-memory/observation-utils.d.ts.map +1 -0
  111. package/dist/processors/observational-memory/observational-memory.d.ts +930 -0
  112. package/dist/processors/observational-memory/observational-memory.d.ts.map +1 -0
  113. package/dist/processors/observational-memory/observer-agent.d.ts +190 -0
  114. package/dist/processors/observational-memory/observer-agent.d.ts.map +1 -0
  115. package/dist/processors/observational-memory/observer-runner.d.ts +141 -0
  116. package/dist/processors/observational-memory/observer-runner.d.ts.map +1 -0
  117. package/dist/processors/observational-memory/operation-registry.d.ts +14 -0
  118. package/dist/processors/observational-memory/operation-registry.d.ts.map +1 -0
  119. package/dist/processors/observational-memory/processor.d.ts +70 -0
  120. package/dist/processors/observational-memory/processor.d.ts.map +1 -0
  121. package/dist/processors/observational-memory/reflector-agent.d.ts +62 -0
  122. package/dist/processors/observational-memory/reflector-agent.d.ts.map +1 -0
  123. package/dist/processors/observational-memory/reflector-runner.d.ts +133 -0
  124. package/dist/processors/observational-memory/reflector-runner.d.ts.map +1 -0
  125. package/dist/processors/observational-memory/repro-capture.d.ts +33 -0
  126. package/dist/processors/observational-memory/repro-capture.d.ts.map +1 -0
  127. package/dist/processors/observational-memory/retry.d.ts +63 -0
  128. package/dist/processors/observational-memory/retry.d.ts.map +1 -0
  129. package/dist/processors/observational-memory/string-utils.d.ts +13 -0
  130. package/dist/processors/observational-memory/string-utils.d.ts.map +1 -0
  131. package/dist/processors/observational-memory/summarize.d.ts +92 -0
  132. package/dist/processors/observational-memory/summarize.d.ts.map +1 -0
  133. package/dist/processors/observational-memory/temporal-markers.d.ts +4 -0
  134. package/dist/processors/observational-memory/temporal-markers.d.ts.map +1 -0
  135. package/dist/processors/observational-memory/temporary-memory.d.ts +8 -0
  136. package/dist/processors/observational-memory/temporary-memory.d.ts.map +1 -0
  137. package/dist/processors/observational-memory/thresholds.d.ts +52 -0
  138. package/dist/processors/observational-memory/thresholds.d.ts.map +1 -0
  139. package/dist/processors/observational-memory/token-counter.d.ts +57 -0
  140. package/dist/processors/observational-memory/token-counter.d.ts.map +1 -0
  141. package/dist/processors/observational-memory/tool-result-helpers.d.ts +12 -0
  142. package/dist/processors/observational-memory/tool-result-helpers.d.ts.map +1 -0
  143. package/dist/processors/observational-memory/tracing.d.ts +17 -0
  144. package/dist/processors/observational-memory/tracing.d.ts.map +1 -0
  145. package/dist/processors/observational-memory/types.d.ts +997 -0
  146. package/dist/processors/observational-memory/types.d.ts.map +1 -0
  147. package/dist/processors/observational-memory/working-memory-extractor.d.ts +5 -0
  148. package/dist/processors/observational-memory/working-memory-extractor.d.ts.map +1 -0
  149. package/dist/processors/working-memory-state/index.d.ts +2 -0
  150. package/dist/processors/working-memory-state/index.d.ts.map +1 -0
  151. package/dist/processors/working-memory-state/processor.d.ts +53 -0
  152. package/dist/processors/working-memory-state/processor.d.ts.map +1 -0
  153. package/dist/src-C1tlhGeW.js +28559 -0
  154. package/dist/src-C1tlhGeW.js.map +1 -0
  155. package/dist/src-DqoifKIy.cjs +28813 -0
  156. package/dist/src-DqoifKIy.cjs.map +1 -0
  157. package/dist/tools/om-tools.d.ts +172 -0
  158. package/dist/tools/om-tools.d.ts.map +1 -0
  159. package/dist/tools/working-memory.d.ts +33 -28
  160. package/dist/tools/working-memory.d.ts.map +1 -1
  161. package/package.json +36 -28
  162. package/dist/index.cjs.map +0 -1
  163. package/dist/index.js.map +0 -1
  164. package/dist/processors/index.cjs.map +0 -1
  165. package/dist/processors/index.js.map +0 -1
  166. package/dist/processors/token-limiter.d.ts +0 -32
  167. package/dist/processors/token-limiter.d.ts.map +0 -1
  168. package/dist/processors/tool-call-filter.d.ts +0 -20
  169. package/dist/processors/tool-call-filter.d.ts.map +0 -1
@@ -0,0 +1,930 @@
1
+ import type { MastraDBMessage, MessageList } from '@mastra/core/agent';
2
+ import type { Mastra } from '@mastra/core/mastra';
3
+ import type { ObservabilityContext } from '@mastra/core/observability';
4
+ import type { ProcessorContext, ProcessorStreamWriter } from '@mastra/core/processors';
5
+ import { MessageHistory } from '@mastra/core/processors';
6
+ import type { RequestContext } from '@mastra/core/request-context';
7
+ import type { MemoryStorage, ObservationalMemoryRecord, ObservationalMemoryHistoryOptions } from '@mastra/core/storage';
8
+ import type { Memory } from '../../index.js';
9
+ import { BufferingCoordinator } from './buffering-coordinator.js';
10
+ /**
11
+ * Returns the parts from the latest step of a message (after the last step-start marker).
12
+ * If no step-start marker exists, returns all parts.
13
+ */
14
+ export declare function getLatestStepParts(parts: MastraDBMessage['content']['parts']): MastraDBMessage['content']['parts'];
15
+ /**
16
+ * Build a messageRange string from the first and last messages that have visible
17
+ * content. Falls back to the full array boundaries when every message is data-only.
18
+ */
19
+ export declare function buildMessageRange(messages: MastraDBMessage[]): string;
20
+ /**
21
+ * Returns the unix-ms timestamp of the last non-data part in the last assistant
22
+ * message, representing when the last visible LLM response completed. Used as the
23
+ * last activity time for activateAfterIdle checks.
24
+ */
25
+ export declare function getLastActivityFromMessages(messages?: MastraDBMessage[]): number | undefined;
26
+ export declare function getLastModelFromMessages(messages?: MastraDBMessage[]): string | undefined;
27
+ export declare function getCurrentModel(model?: {
28
+ provider?: string;
29
+ modelId?: string;
30
+ }): string | undefined;
31
+ export { didProviderChange } from './model-context.js';
32
+ import { ObservationTurn } from './observation-turn/index.js';
33
+ import type { ObservationTurnHooks } from './observation-turn/types.js';
34
+ import { ObserverRunner } from './observer-runner.js';
35
+ import type { CompressionLevel } from './reflector-agent.js';
36
+ import { ReflectorRunner } from './reflector-runner.js';
37
+ import { TokenCounter } from './token-counter.js';
38
+ import type { ObservationDebugEvent, ObservationalMemoryConfig, ObserveHookContext, ObserveHookUsage, ObserveHooks, ObserveTrigger, ResolvedObservationConfig, ResolvedReflectionConfig, ThresholdRange, ObservationModelContext } from './types.js';
39
+ /**
40
+ * ObservationalMemory - A three-agent memory system for long conversations.
41
+ *
42
+ * This processor:
43
+ * 1. On input: Injects observations into context, filters out observed messages
44
+ * 2. On output: Tracks new messages, triggers Observer/Reflector when thresholds hit
45
+ *
46
+ * The Actor (main agent) sees:
47
+ * - Observations (compressed history)
48
+ * - Suggested continuation message
49
+ * - Recent unobserved messages
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * import { ObservationalMemory } from '@mastra/memory/processors';
54
+ *
55
+ * // Minimal configuration
56
+ * const om = new ObservationalMemory({ storage });
57
+ *
58
+ * // Full configuration
59
+ * const om = new ObservationalMemory({
60
+ * storage,
61
+ * model: 'google/gemini-2.5-flash', // shared model for both agents
62
+ * shareTokenBudget: true,
63
+ * observation: {
64
+ * messageTokens: 30_000,
65
+ * modelSettings: { temperature: 0.3 },
66
+ * },
67
+ * reflection: {
68
+ * observationTokens: 40_000,
69
+ * },
70
+ * });
71
+ *
72
+ * const agent = new Agent({
73
+ * inputProcessors: [om],
74
+ * outputProcessors: [om],
75
+ * });
76
+ * ```
77
+ */
78
+ export declare class ObservationalMemory {
79
+ private storage;
80
+ private tokenCounter;
81
+ readonly scope: 'resource' | 'thread';
82
+ /** Whether retrieval-mode observation groups are enabled. */
83
+ readonly retrieval: boolean;
84
+ /** Scope the recall tool was registered with — controls which retrieval instructions are injected. */
85
+ readonly retrievalScope: 'thread' | 'resource';
86
+ /** Application-provided guidance appended after the native retrieval instructions. */
87
+ private retrievalInstructions?;
88
+ private retrievalSearch;
89
+ private observationConfig;
90
+ private reflectionConfig;
91
+ private onDebugEvent?;
92
+ readonly onIndexObservations?: (observation: {
93
+ text: string;
94
+ groupId: string;
95
+ range: string;
96
+ threadId: string;
97
+ resourceId: string;
98
+ observedAt?: Date;
99
+ }) => Promise<void>;
100
+ /** Config-level lifecycle hooks fired for every observation/reflection cycle. */
101
+ readonly hooks?: ObserveHooks;
102
+ /** Observer agent runner — handles LLM calls for extracting observations. */
103
+ readonly observer: ObserverRunner;
104
+ /** Reflector agent runner — handles LLM calls for compressing observations. */
105
+ readonly reflector: ReflectorRunner;
106
+ /** Buffering state coordinator — manages static maps and buffering lifecycle. */
107
+ readonly buffering: BufferingCoordinator;
108
+ private shouldObscureThreadIds;
109
+ private hasher;
110
+ private mastra?;
111
+ private memory?;
112
+ /**
113
+ * Track message IDs observed during this instance's lifetime.
114
+ * Prevents re-observing messages when per-thread lastObservedAt cursors
115
+ * haven't fully advanced past messages observed in a prior cycle.
116
+ * @internal Used by observation strategies. Do not call directly.
117
+ */
118
+ observedMessageIds: Set<string>;
119
+ /** Internal MessageHistory for message persistence */
120
+ private messageHistory;
121
+ /**
122
+ * In-memory mutex for serializing observation/reflection cycles per resource/thread.
123
+ * Prevents race conditions where two concurrent cycles could both read isObserving=false
124
+ * before either sets it to true, leading to lost work.
125
+ *
126
+ * Key format: "resource:{resourceId}" or "thread:{threadId}"
127
+ * Value: Promise that resolves when the lock is released
128
+ *
129
+ * NOTE: This mutex only works within a single Node.js process. For distributed
130
+ * deployments, external locking (Redis, database locks) would be needed, or
131
+ * accept eventual consistency (acceptable for v1).
132
+ */
133
+ private locks;
134
+ /**
135
+ * Initial record lookup/creation promises keyed by the effective storage scope.
136
+ * Concurrent callers share the full read-or-create operation so a stale read
137
+ * cannot create another generation-zero record after the first insert finishes.
138
+ * Entries are removed after both success and failure so later calls always
139
+ * re-read storage and transient failures can be retried.
140
+ */
141
+ private recordInitializations;
142
+ /**
143
+ * Acquire a lock for the given key, execute the callback, then release.
144
+ * If a lock is already held, waits for it to be released before acquiring.
145
+ */
146
+ private withLock;
147
+ constructor(config: ObservationalMemoryConfig);
148
+ __registerMastra(mastra: Mastra): void;
149
+ /**
150
+ * Get the current configuration for this OM instance.
151
+ * Used by the server to expose config to the UI when OM is added via processors.
152
+ */
153
+ get config(): {
154
+ scope: 'resource' | 'thread';
155
+ retrieval: boolean;
156
+ observation: {
157
+ messageTokens: number | ThresholdRange;
158
+ previousObserverTokens: number | false | undefined;
159
+ };
160
+ reflection: {
161
+ observationTokens: number | ThresholdRange;
162
+ };
163
+ };
164
+ /**
165
+ * Wait for any in-flight async buffering operations for the given thread/resource.
166
+ * Used by server endpoints to block until buffering completes so the UI can get final state.
167
+ */
168
+ waitForBuffering(threadId: string | null | undefined, resourceId: string | null | undefined, timeoutMs?: number): Promise<void>;
169
+ private getConcreteModel;
170
+ private getModelToResolve;
171
+ private formatModelName;
172
+ private resolveObservationModel;
173
+ private resolveReflectionModel;
174
+ private resolveTieredModel;
175
+ private resolveModelRouting;
176
+ private resolveModelContext;
177
+ /**
178
+ * Get the default compression start level based on model behavior.
179
+ * gemini-2.5-flash is a faithful transcriber that needs explicit pressure to compress effectively.
180
+ */
181
+ getCompressionStartLevel(requestContext?: RequestContext): Promise<CompressionLevel>;
182
+ /**
183
+ * Get the full config including resolved model names.
184
+ * This is async because it needs to resolve the model configs.
185
+ */
186
+ getResolvedConfig(requestContext?: RequestContext): Promise<{
187
+ scope: 'resource' | 'thread';
188
+ observation: {
189
+ messageTokens: number | ThresholdRange;
190
+ model: string;
191
+ previousObserverTokens: number | false | undefined;
192
+ routing?: Array<{
193
+ upTo: number;
194
+ model: string;
195
+ }>;
196
+ };
197
+ reflection: {
198
+ observationTokens: number | ThresholdRange;
199
+ model: string;
200
+ routing?: Array<{
201
+ upTo: number;
202
+ model: string;
203
+ }>;
204
+ };
205
+ }>;
206
+ /**
207
+ * Emit a debug event if the callback is configured.
208
+ * @internal Used by observation strategies. Do not call directly.
209
+ */
210
+ emitDebugEvent(event: ObservationDebugEvent): void;
211
+ /**
212
+ * Validate buffer configuration on first use.
213
+ * Ensures bufferTokens is less than the threshold and bufferActivation is valid.
214
+ */
215
+ private validateBufferConfig;
216
+ /**
217
+ * Resolve the effective messageTokens for a record.
218
+ * Only explicit per-record overrides (stored under `_overrides`) win;
219
+ * the initial config snapshot written by getOrCreateRecord() is ignored
220
+ * so that later instance-level changes still take effect.
221
+ *
222
+ * Overrides that fall below the instance-level buffering floor
223
+ * (bufferTokens / absolute bufferActivation) are clamped to the
224
+ * instance threshold to preserve buffering invariants.
225
+ */
226
+ private getEffectiveMessageTokens;
227
+ /**
228
+ * Resolve the effective reflection observationTokens for a record.
229
+ * Only explicit per-record overrides (stored under `_overrides`) win;
230
+ * the initial config snapshot is ignored so instance-level changes
231
+ * still take effect for existing records.
232
+ */
233
+ private getEffectiveReflectionTokens;
234
+ /**
235
+ * Check whether the unobserved message tokens meet the observation threshold.
236
+ */
237
+ private meetsObservationThreshold;
238
+ /**
239
+ * Get thread/resource IDs for storage lookup
240
+ */
241
+ private getStorageIds;
242
+ /**
243
+ * Get or create the observational memory record.
244
+ * Returns the existing record if one exists, otherwise initializes a new one.
245
+ */
246
+ getOrCreateRecord(threadId: string, resourceId?: string): Promise<ObservationalMemoryRecord>;
247
+ /**
248
+ * Get current config snapshot for observation markers.
249
+ */
250
+ private getObservationMarkerConfig;
251
+ /**
252
+ * Persist a data-om-* marker part on the last assistant message in messageList
253
+ * AND save the updated message to the DB so it survives page reload.
254
+ * (data-* parts are filtered out before sending to the LLM, so they don't affect model calls.)
255
+ * @internal Used by ReflectorRunner. Do not call directly.
256
+ */
257
+ persistMarkerToMessage(marker: {
258
+ type: string;
259
+ data: unknown;
260
+ }, messageList: MessageList | undefined, threadId: string, resourceId?: string): Promise<void>;
261
+ /**
262
+ * Persist a marker to the last assistant message in storage.
263
+ * Unlike persistMarkerToMessage, this fetches messages directly from the DB
264
+ * so it works even when no MessageList is available (e.g. async buffering ops).
265
+ * @internal Used by observation strategies. Do not call directly.
266
+ */
267
+ persistMarkerToStorage(marker: {
268
+ type: string;
269
+ data: unknown;
270
+ }, threadId: string, resourceId?: string): Promise<void>;
271
+ /**
272
+ * Find the last completed observation boundary in a message's parts.
273
+ * A completed observation is a start marker followed by an end marker.
274
+ *
275
+ * Returns the index of the END marker (which is the observation boundary),
276
+ * or -1 if no completed observation is found.
277
+ */
278
+ /**
279
+ * Check if a message has an in-progress observation (start without end).
280
+ */
281
+ private hasInProgressObservation;
282
+ /**
283
+ * Seal messages to prevent new parts from being merged into them.
284
+ * This is used when starting buffering to capture the current content state.
285
+ *
286
+ * Sealing works by:
287
+ * 1. Setting `message.content.metadata.mastra.sealed = true` (message-level flag)
288
+ * 2. Adding `metadata.mastra.sealedAt` to the last part (boundary marker)
289
+ *
290
+ * When MessageList.add() receives a message with the same ID as a sealed message,
291
+ * it creates a new message with only the parts beyond the seal boundary.
292
+ *
293
+ * The messages are mutated in place - since they're references to the same objects
294
+ * in the MessageList, the seal will be recognized immediately.
295
+ *
296
+ * @param messages - Messages to seal (mutated in place)
297
+ */
298
+ /** @internal Used by ObservationStep. */
299
+ sealMessagesForBuffering(messages: MastraDBMessage[]): void;
300
+ /**
301
+ * Insert an observation marker into a message.
302
+ * The marker is appended directly to the message's parts array (mutating in place).
303
+ * Also persists the change to storage so markers survive page refresh.
304
+ *
305
+ * For end/failed markers, the message is also "sealed" to prevent future content
306
+ * from being merged into it. This ensures observation markers are preserved.
307
+ */
308
+ /**
309
+ * Insert an observation marker into a message.
310
+ * For start markers, this pushes the part directly.
311
+ * For end/failed markers, this should be called AFTER writer.custom() has added the part,
312
+ * so we just find the part and add sealing metadata.
313
+ */
314
+ /**
315
+ * Create a virtual message containing only the unobserved parts.
316
+ * This is used for token counting and observation.
317
+ */
318
+ private createUnobservedMessage;
319
+ /**
320
+ * Get unobserved messages with part-level filtering.
321
+ *
322
+ * This method uses data-om-observation-end markers to filter at the part level:
323
+ * 1. For messages WITH a completed observation: only return parts AFTER the end marker
324
+ * 2. For messages WITHOUT completed observation: check timestamp against lastObservedAt
325
+ *
326
+ * This handles the case where a single message accumulates many parts
327
+ * (like tool calls) during an agentic loop - we only observe the new parts.
328
+ */
329
+ /** @internal Used by ObservationStep. */
330
+ getUnobservedMessages(allMessages: MastraDBMessage[], record: ObservationalMemoryRecord, opts?: {
331
+ excludeBuffered?: boolean;
332
+ }): MastraDBMessage[];
333
+ /**
334
+ * Prepare optimized observer context by applying truncation and buffered-reflection inclusion.
335
+ *
336
+ * Returns the (possibly optimized) observations string to pass as "Previous Observations"
337
+ * to the observer prompt. When no optimization options are set, returns the input unchanged.
338
+ */
339
+ prepareObserverContext(existingObservations: string | undefined, record?: ObservationalMemoryRecord | null): {
340
+ context: string | undefined;
341
+ wasTruncated: boolean;
342
+ };
343
+ /**
344
+ * Truncate observations to fit within a token budget.
345
+ *
346
+ * Strategy:
347
+ * 1. Keep a raw tail of recent observations (end of block).
348
+ * 2. Add a truncation marker: [X observations truncated here], placed at the hidden gap.
349
+ * 3. Try to preserve important observations (🔴) from older context, newest-first.
350
+ * 4. Enforce that at least 50% of kept observations remain raw tail observations.
351
+ */
352
+ private truncateObservationsToTokenBudget;
353
+ /**
354
+ * Format observations for injection into context.
355
+ * Applies token optimization before presenting to the Actor.
356
+ *
357
+ * In resource scope mode, filters continuity messages to only show
358
+ * the message for the current thread.
359
+ */
360
+ private formatObservationsForContext;
361
+ private splitObservationContextChunks;
362
+ /**
363
+ * Create a message boundary delimiter with an ISO 8601 date.
364
+ * The date should be the lastObservedAt timestamp — the latest message
365
+ * timestamp that was observed to produce the observations following this boundary.
366
+ */
367
+ static createMessageBoundary(date: Date): string;
368
+ /**
369
+ * Get threadId and resourceId from either RequestContext or MessageList
370
+ */
371
+ getThreadContext(requestContext: RequestContext | undefined, messageList: MessageList): {
372
+ threadId: string;
373
+ resourceId?: string;
374
+ } | null;
375
+ /**
376
+ * Save messages to storage, skipping messages that were already persisted by
377
+ * async buffering. Uses the message-level sealed flag (metadata.mastra.sealed)
378
+ * to detect already-persisted messages, avoiding redundant DB operations.
379
+ *
380
+ * Messages with observation markers are always saved (upserted) even if sealed,
381
+ * because the markers need to be persisted to storage.
382
+ */
383
+ persistMessages(messagesToSave: MastraDBMessage[], threadId: string, resourceId: string | undefined): Promise<void>;
384
+ /**
385
+ * Load messages from storage that haven't been observed yet.
386
+ * Uses cursor-based query with lastObservedAt timestamp for efficiency.
387
+ *
388
+ * In resource scope mode, loads messages for the entire resource (all threads).
389
+ * In thread scope mode, loads messages for just the current thread.
390
+ */
391
+ private loadMessagesFromStorage;
392
+ /**
393
+ * Format unobserved messages from other threads as <unobserved-context> blocks.
394
+ * These are injected into the Actor's context so it has awareness of activity
395
+ * in other threads for the same resource.
396
+ */
397
+ private formatUnobservedContextBlocks;
398
+ private representThreadIDInContext;
399
+ /**
400
+ * Get the maximum createdAt timestamp from a list of messages.
401
+ * Used to set lastObservedAt to the most recent message timestamp instead of current time.
402
+ * This ensures historical data (like LongMemEval fixtures) works correctly.
403
+ */
404
+ private getMaxMessageTimestamp;
405
+ /**
406
+ * Wrap observations in a thread attribution tag.
407
+ * Used in resource scope to track which thread observations came from.
408
+ * @internal Used by observation strategies. Do not call directly.
409
+ */
410
+ wrapWithThreadTag(threadId: string, observations: string, messageRange?: string): Promise<string>;
411
+ /**
412
+ * Append or merge new thread sections.
413
+ * If the new section has the same thread ID and date as an existing section,
414
+ * merge the observations into that section to reduce token usage.
415
+ * Otherwise, append as a new section.
416
+ */
417
+ private replaceOrAppendThreadSection;
418
+ /**
419
+ * @internal Used by observation strategies. Do not call directly.
420
+ */
421
+ wrapObservations(rawObservations: string, existingObservations: string, threadId: string, lastObservedAt?: Date, messageRange?: string): Promise<string> | string;
422
+ /**
423
+ * Start an async background observation that stores results to bufferedObservations.
424
+ * This is a fire-and-forget operation that runs in the background.
425
+ * The results will be swapped to active when the main threshold is reached.
426
+ *
427
+ * If another buffering operation is already in progress for this scope, this will
428
+ * wait for it to complete before starting a new one (mutex behavior).
429
+ *
430
+ * @param record - Current OM record
431
+ * @param threadId - Thread ID
432
+ * @param unobservedMessages - All unobserved messages (will be filtered for already-buffered)
433
+ * @param lockKey - Lock key for this scope
434
+ * @param writer - Optional stream writer for emitting buffering markers
435
+ */
436
+ private startAsyncBufferedObservation;
437
+ /**
438
+ * Internal method that waits for existing buffering operation and then runs new buffering.
439
+ * This implements the mutex-wait behavior.
440
+ */
441
+ private runAsyncBufferedObservation;
442
+ /**
443
+ * Trigger async buffered observation if the token count has crossed a new interval.
444
+ *
445
+ * Encapsulates the shouldTrigger check + startAsyncBufferedObservation call.
446
+ * Returns whether buffering was actually triggered.
447
+ */
448
+ triggerAsyncBuffering(opts: {
449
+ threadId: string;
450
+ resourceId?: string;
451
+ record: ObservationalMemoryRecord;
452
+ pendingTokens: number;
453
+ unbufferedPendingTokens: number;
454
+ unobservedMessages: MastraDBMessage[];
455
+ threshold: number;
456
+ writer?: ProcessorStreamWriter;
457
+ requestContext?: RequestContext;
458
+ observabilityContext?: ObservabilityContext;
459
+ }): Promise<boolean>;
460
+ private isMessageList;
461
+ private removeIdsFromArray;
462
+ /**
463
+ * Mutate partially observed messages in place and return the fully observed
464
+ * message IDs that should be removed from the live context.
465
+ *
466
+ * This is the shared activation-cleanup primitive used by both the processor
467
+ * and AI SDK integrations: callers pass the current live messages, OM trims
468
+ * any partially observed messages down to their unobserved parts, and OM
469
+ * returns only the IDs that are safe to remove entirely.
470
+ */
471
+ getObservedMessageIdsForCleanup(opts: {
472
+ threadId: string;
473
+ resourceId?: string;
474
+ messages: MastraDBMessage[];
475
+ observedMessageIds?: string[];
476
+ retentionFloor?: number;
477
+ /** Message ids that must never be removed (e.g. the in-flight turn's pending messages). */
478
+ preserveMessageIds?: string[];
479
+ }): Promise<string[]>;
480
+ /**
481
+ * Clean up observed content from either a live MessageList or a plain message array.
482
+ *
483
+ * - MessageList input: mutates the live container in place and returns the remaining messages
484
+ * - Array input: mutates the array in place and returns it
485
+ *
486
+ * This is the shared cleanup primitive intended for both processor and non-processor
487
+ * integrations. The processor may still pass sealedIds/state so marker/fallback cleanup
488
+ * can persist messages safely, but callers that do not need that bookkeeping can omit it.
489
+ */
490
+ /** @internal Used by ObservationStep. */
491
+ cleanupMessages(opts: {
492
+ threadId: string;
493
+ resourceId?: string;
494
+ messages: MessageList | MastraDBMessage[];
495
+ observedMessageIds?: string[];
496
+ retentionFloor?: number;
497
+ /** Message ids that must never be removed (e.g. the in-flight turn's pending messages). */
498
+ preserveMessageIds?: string[];
499
+ }): Promise<MastraDBMessage[]>;
500
+ /**
501
+ * Clean up the message context after a successful observation.
502
+ *
503
+ * Handles both activation-based cleanup (using observedMessageIds) and
504
+ * marker-based cleanup (using observation boundary markers). Respects
505
+ * retention floors to prevent removing too many messages.
506
+ */
507
+ cleanupObservedContext(opts: {
508
+ messageList: MessageList;
509
+ threadId: string;
510
+ resourceId?: string;
511
+ observedMessageIds?: string[];
512
+ retentionFloor?: number;
513
+ }): Promise<void>;
514
+ /**
515
+ * Reset buffering state after a successful observation activation.
516
+ *
517
+ * Clears the lastBufferedBoundary, buffering flag, and optionally cleans up
518
+ * static maps for activated message IDs.
519
+ */
520
+ /** @internal Used by ObservationStep. */
521
+ resetBufferingState(opts: {
522
+ threadId: string;
523
+ resourceId?: string;
524
+ recordId: string;
525
+ activatedMessageIds?: string[];
526
+ }): Promise<void>;
527
+ /**
528
+ * Build the observation system message string for injection into an LLM prompt.
529
+ *
530
+ * Loads thread metadata (currentTask, suggestedResponse), formats observations
531
+ * with context prompts and instructions, and returns the fully-formed string.
532
+ * Returns undefined if no observations exist.
533
+ *
534
+ * This is the public entry point for context formatting — used by both
535
+ * Memory.getContext() (standalone) and the processor (via injectObservationsIntoMessages).
536
+ *
537
+ * @example
538
+ * ```ts
539
+ * const systemMsg = await om.buildContextSystemMessage({ threadId: 'thread-1' });
540
+ * if (systemMsg) {
541
+ * const result = await generateText({ system: systemMsg, messages });
542
+ * }
543
+ * ```
544
+ */
545
+ buildContextSystemMessage(opts: {
546
+ threadId: string;
547
+ resourceId?: string;
548
+ record?: ObservationalMemoryRecord;
549
+ unobservedContextBlocks?: string;
550
+ currentDate?: Date;
551
+ }): Promise<string | undefined>;
552
+ /**
553
+ * Build observation context as an array of system message chunks.
554
+ * Each chunk is a separate system message for better LLM cache hit rates.
555
+ * Used by the processor to inject multiple system messages.
556
+ * @internal
557
+ */
558
+ buildContextSystemMessages(opts: {
559
+ threadId: string;
560
+ resourceId?: string;
561
+ record?: ObservationalMemoryRecord;
562
+ unobservedContextBlocks?: string;
563
+ currentDate?: Date;
564
+ }): Promise<string[] | undefined>;
565
+ /**
566
+ * Get unobserved messages from other threads for resource-scoped observation.
567
+ *
568
+ * Lists all threads for the resource, filters to unobserved messages,
569
+ * and formats them as context blocks.
570
+ */
571
+ /** @internal Used by ObservationTurn. */
572
+ getOtherThreadsContext(resourceId: string, currentThreadId: string): Promise<string | undefined>;
573
+ /**
574
+ * Emit debug event and stream progress for UI feedback.
575
+ */
576
+ emitProgress(opts: {
577
+ record: ObservationalMemoryRecord;
578
+ pendingTokens: number;
579
+ threshold: number;
580
+ effectiveObservationTokensThreshold: number;
581
+ currentObservationTokens: number;
582
+ writer?: ProcessorStreamWriter;
583
+ stepNumber: number;
584
+ threadId: string;
585
+ resourceId?: string;
586
+ }): Promise<void>;
587
+ /**
588
+ * Get the current observation status for a thread/resource.
589
+ *
590
+ * Loads unobserved messages from storage, counts tokens, and checks against
591
+ * configured thresholds. Returns a comprehensive status object that tells the
592
+ * caller what actions are needed.
593
+ *
594
+ * This is a pure read operation with no side effects.
595
+ *
596
+ * @example
597
+ * ```ts
598
+ * const status = await om.getStatus({ threadId });
599
+ * if (status.shouldObserve) {
600
+ * await om.observe({ threadId });
601
+ * } else if (status.shouldBuffer) {
602
+ * await om.buffer({ threadId });
603
+ * }
604
+ * if (status.shouldReflect) {
605
+ * await om.reflect(threadId);
606
+ * }
607
+ * ```
608
+ */
609
+ getStatus(opts: {
610
+ threadId: string;
611
+ resourceId?: string;
612
+ messages?: MastraDBMessage[];
613
+ }): Promise<{
614
+ record: ObservationalMemoryRecord;
615
+ pendingTokens: number;
616
+ threshold: number;
617
+ effectiveObservationTokensThreshold: number;
618
+ unbufferedPendingTokens: number;
619
+ shouldObserve: boolean;
620
+ shouldBuffer: boolean;
621
+ shouldReflect: boolean;
622
+ bufferedChunkCount: number;
623
+ bufferedChunkTokens: number;
624
+ canActivate: boolean;
625
+ asyncObservationEnabled: boolean;
626
+ asyncReflectionEnabled: boolean;
627
+ scope: 'resource' | 'thread';
628
+ }>;
629
+ /**
630
+ * Finalize the observation lifecycle: activate any remaining buffered chunks,
631
+ * then observe if the threshold is crossed.
632
+ *
633
+ * Call this at the end of a conversation, session, or turn sequence to ensure
634
+ * no buffered observations are left orphaned and the observation cursor is
635
+ * advanced. Produces a clean terminal state (no pending chunks, cursor up to date).
636
+ *
637
+ * @example
638
+ * ```ts
639
+ * // After all turns are complete
640
+ * const result = await om.finalize({ threadId });
641
+ * // result.activated: true if buffered chunks were promoted
642
+ * // result.observed: true if a full observation pass ran
643
+ * ```
644
+ */
645
+ finalize(opts: {
646
+ threadId: string;
647
+ resourceId?: string;
648
+ messages?: MastraDBMessage[];
649
+ }): Promise<{
650
+ activated: boolean;
651
+ observed: boolean;
652
+ reflected: boolean;
653
+ record: ObservationalMemoryRecord;
654
+ }>;
655
+ /**
656
+ * Return only the messages that haven't been fully observed yet.
657
+ *
658
+ * Use this to prune observed messages from an in-memory message array,
659
+ * preventing unbounded context growth across steps in a multi-step loop.
660
+ * This is the array-based equivalent of the processor's `cleanupObservedContext()`.
661
+ *
662
+ * @example
663
+ * ```ts
664
+ * // In a prepareStep hook, prune before sending to the model
665
+ * messages = await om.pruneObserved({ threadId, messages });
666
+ * ```
667
+ */
668
+ pruneObserved(opts: {
669
+ threadId: string;
670
+ resourceId?: string;
671
+ messages: MastraDBMessage[];
672
+ }): Promise<MastraDBMessage[]>;
673
+ /**
674
+ * Load unobserved messages from storage for a thread/resource.
675
+ *
676
+ * Fetches the OM record, queries storage for messages after the
677
+ * lastObservedAt cursor, then applies part-level filtering so
678
+ * partially-observed messages only include their unobserved parts.
679
+ *
680
+ * Use this when you need to load stored conversation history that
681
+ * hasn't been observed yet (e.g. in a stateless gateway proxy that
682
+ * only receives the latest message from the HTTP request).
683
+ */
684
+ loadUnobservedMessages(opts: {
685
+ threadId: string;
686
+ resourceId?: string;
687
+ }): Promise<MastraDBMessage[]>;
688
+ /**
689
+ * Create a buffered observation chunk without merging into active observations.
690
+ *
691
+ * Loads unobserved messages from storage (filtered by the buffer cursor to avoid
692
+ * re-buffering), calls the observer LLM, and stores the result as a pending
693
+ * buffered chunk in the DB. The chunk can later be merged into active observations
694
+ * via `activate()`.
695
+ *
696
+ * This is a synchronous (awaited) operation — the caller decides whether to
697
+ * `await` it or fire-and-forget. All state lives in storage; no in-process
698
+ * coordination is needed.
699
+ *
700
+ * @example
701
+ * ```ts
702
+ * const status = await om.getStatus({ threadId });
703
+ * if (status.shouldBuffer) {
704
+ * await om.buffer({ threadId });
705
+ * }
706
+ * ```
707
+ */
708
+ /** @internal Used by ObservationStep. */
709
+ buffer(opts: {
710
+ threadId: string;
711
+ resourceId?: string;
712
+ messages?: MastraDBMessage[];
713
+ /** The freshly-counted pending token count from the caller. If not provided,
714
+ * falls back to record.pendingMessageTokens (which may be stale). */
715
+ pendingTokens?: number;
716
+ /** Pre-loaded record to skip the initial getOrCreateRecord() fetch.
717
+ * When called fire-and-forget, passing the record avoids an async gap
718
+ * before lastBufferedBoundary is set. */
719
+ record?: ObservationalMemoryRecord;
720
+ writer?: ProcessorStreamWriter;
721
+ agent?: ProcessorContext['agent'];
722
+ sendSignal?: ProcessorContext['sendSignal'];
723
+ requestContext?: RequestContext;
724
+ currentModel?: ObservationModelContext;
725
+ observabilityContext?: ObservabilityContext;
726
+ /** Allow idle-triggered buffering to observe any non-empty candidate set. */
727
+ skipMinimumTokenCheck?: boolean;
728
+ /** Called with the final candidate messages after cursor filtering, before the observer runs.
729
+ * Use this to seal messages in a live MessageList and persist them to storage. */
730
+ beforeBuffer?: (candidates: MastraDBMessage[]) => Promise<void>;
731
+ }): Promise<{
732
+ buffered: boolean;
733
+ record: ObservationalMemoryRecord;
734
+ }>;
735
+ /**
736
+ * Activate buffered observation chunks by merging them into active observations.
737
+ *
738
+ * This is a pure storage operation — no LLM call. It reads buffered chunks from
739
+ * the DB and swaps them into active observations via `storage.swapBufferedToActive()`.
740
+ *
741
+ * Call this after `buffer()` has created chunks, typically at the start of a new
742
+ * turn or when `getStatus().canActivate` is true.
743
+ *
744
+ * @example
745
+ * ```ts
746
+ * const status = await om.getStatus({ threadId });
747
+ * if (status.canActivate) {
748
+ * const result = await om.activate({ threadId });
749
+ * if (result.activated) {
750
+ * console.log('Activated', result.activatedMessageIds?.length, 'message observations');
751
+ * }
752
+ * }
753
+ * ```
754
+ */
755
+ /** @internal Used by ObservationStep. */
756
+ activate(opts: {
757
+ threadId: string;
758
+ resourceId?: string;
759
+ /** When true, skip activation if pending tokens are below the observation threshold. */
760
+ checkThreshold?: boolean;
761
+ /** Messages to use for threshold check (in-memory). If omitted, loads from storage. */
762
+ messages?: MastraDBMessage[];
763
+ /** Current actor model for provider-change activation checks. */
764
+ currentModel?: ObservationModelContext;
765
+ /** Stream writer for emitting activation markers to the UI. */
766
+ writer?: ProcessorStreamWriter;
767
+ /** MessageList for persisting activation markers on the last assistant message. */
768
+ messageList?: MessageList;
769
+ }): Promise<{
770
+ activated: boolean;
771
+ record: ObservationalMemoryRecord;
772
+ activatedMessageIds?: string[];
773
+ }>;
774
+ /**
775
+ * Compose the config-level hooks with optional per-call hooks into a single
776
+ * `ObserveHooks` object, binding call context onto the config-level
777
+ * callbacks. Config-level hooks are guarded so a throwing consumer hook can
778
+ * never fail an observation/reflection cycle; per-call hooks keep their
779
+ * existing payloads and propagation semantics. Returns undefined when
780
+ * neither is configured, so call sites stay zero-cost.
781
+ *
782
+ * Used internally by every pipeline path (manual observe/reflect,
783
+ * turn-engine sync observation, async buffering); public only so the
784
+ * observation turn engine can thread config-level reflection hooks into
785
+ * reflector calls.
786
+ *
787
+ * @internal
788
+ */
789
+ composeHooks(callHooks: ObserveHooks | undefined, context: ObserveHookContext): ObserveHooks | undefined;
790
+ /**
791
+ * Run one buffered observation cycle, firing config-level hooks around it.
792
+ * Shared by both async-buffer lanes — buffer() and
793
+ * runAsyncBufferedObservation() — whose fire-and-forget callers never see
794
+ * the strategy result. The async-buffer strategy swallows failures
795
+ * (rethrowOnFailure=false) and surfaces them on the result instead, so the
796
+ * end hook reports `error` for failed cycles even though nothing throws.
797
+ */
798
+ private runBufferedObservationCycle;
799
+ /**
800
+ * Manually trigger observation.
801
+ *
802
+ * When `messages` is provided, those are used directly (filtered for unobserved)
803
+ * instead of reading from storage. This allows external systems (e.g., opencode)
804
+ * to pass conversation messages without duplicating them into Mastra's DB.
805
+ *
806
+ * Returns a result indicating whether observation and/or reflection occurred,
807
+ * along with the updated record.
808
+ */
809
+ observe(opts: {
810
+ threadId: string;
811
+ resourceId?: string;
812
+ messages?: MastraDBMessage[];
813
+ /** Live MessageList for the in-flight turn — lets markers land on the pending assistant message. */
814
+ messageList?: MessageList;
815
+ hooks?: ObserveHooks;
816
+ /** Which pipeline path initiated this cycle; defaults to 'manual'. */
817
+ trigger?: ObserveTrigger;
818
+ agent?: ProcessorContext['agent'];
819
+ requestContext?: RequestContext;
820
+ writer?: ProcessorStreamWriter;
821
+ observabilityContext?: ObservabilityContext;
822
+ }): Promise<{
823
+ observed: boolean;
824
+ reflected: boolean;
825
+ record: ObservationalMemoryRecord;
826
+ }>;
827
+ /**
828
+ * Manually trigger reflection with optional guidance prompt.
829
+ *
830
+ * @example
831
+ * ```ts
832
+ * // Trigger reflection with specific focus
833
+ * await om.reflect(threadId, resourceId,
834
+ * "focus on the authentication implementation, only keep minimal details about UI styling"
835
+ * );
836
+ * ```
837
+ */
838
+ reflect(threadId: string, resourceId?: string, prompt?: string, requestContext?: RequestContext, observabilityContext?: ObservabilityContext): Promise<{
839
+ reflected: boolean;
840
+ record: ObservationalMemoryRecord;
841
+ usage?: ObserveHookUsage;
842
+ }>;
843
+ /**
844
+ * Get current observations for a thread/resource
845
+ */
846
+ getObservations(threadId: string, resourceId?: string): Promise<string | undefined>;
847
+ /**
848
+ * Get current record for a thread/resource
849
+ */
850
+ getRecord(threadId: string, resourceId?: string): Promise<ObservationalMemoryRecord | null>;
851
+ /**
852
+ * Update per-record config overrides for observation and/or reflection thresholds.
853
+ * The provided config is deep-merged into the record's `_overrides` key,
854
+ * so you only need to specify the fields you want to change.
855
+ *
856
+ * Overrides that violate buffering invariants (e.g. messageTokens below
857
+ * bufferTokens) are silently ignored at read time — the helpers fall back
858
+ * to the instance-level config.
859
+ *
860
+ * @example
861
+ * ```ts
862
+ * await om.updateRecordConfig('thread-1', undefined, {
863
+ * observation: { messageTokens: 2000 },
864
+ * reflection: { observationTokens: 8000 },
865
+ * });
866
+ * ```
867
+ */
868
+ updateRecordConfig(threadId: string, resourceId: string | undefined, config: Record<string, unknown>): Promise<void>;
869
+ /**
870
+ * Get observation history (previous generations)
871
+ */
872
+ getHistory(threadId: string, resourceId?: string, limit?: number, options?: ObservationalMemoryHistoryOptions): Promise<ObservationalMemoryRecord[]>;
873
+ /**
874
+ * Clear all memory for a specific thread/resource
875
+ */
876
+ clear(threadId: string, resourceId?: string): Promise<void>;
877
+ /**
878
+ * Get the underlying storage adapter
879
+ */
880
+ getStorage(): MemoryStorage;
881
+ /**
882
+ * Get the owning Memory instance when available.
883
+ */
884
+ getMemory(): Memory | undefined;
885
+ /**
886
+ * Get the token counter
887
+ */
888
+ getTokenCounter(): TokenCounter;
889
+ /**
890
+ * Get current observation configuration
891
+ */
892
+ getObservationConfig(): ResolvedObservationConfig;
893
+ /**
894
+ * Get current reflection configuration
895
+ */
896
+ getReflectionConfig(): ResolvedReflectionConfig;
897
+ /**
898
+ * Get the message history instance for marker persistence.
899
+ */
900
+ getMessageHistory(): MessageHistory;
901
+ /**
902
+ * Get whether thread IDs should be obscured in observations.
903
+ */
904
+ getObscureThreadIds(): boolean;
905
+ /**
906
+ * Begin a new observation turn — the high-level API for managing the
907
+ * observe/buffer/activate/reflect lifecycle across agentic loop steps.
908
+ *
909
+ * @example
910
+ * ```ts
911
+ * const turn = om.beginTurn({ threadId, resourceId, messageList });
912
+ * await turn.start(memory);
913
+ *
914
+ * const step0 = turn.step(0);
915
+ * const ctx = await step0.prepare();
916
+ * // ... agent generates ...
917
+ *
918
+ * await turn.end();
919
+ * ```
920
+ */
921
+ beginTurn(opts: {
922
+ threadId: string;
923
+ resourceId?: string;
924
+ messageList: MessageList;
925
+ agent?: ProcessorContext['agent'];
926
+ observabilityContext?: ObservabilityContext;
927
+ hooks?: ObservationTurnHooks;
928
+ }): ObservationTurn;
929
+ }
930
+ //# sourceMappingURL=observational-memory.d.ts.map