@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,997 @@
1
+ import type { AgentConfig } from '@mastra/core/agent';
2
+ import type { Mastra } from '@mastra/core/mastra';
3
+ import type { ObservationalMemoryModelSettings } from '@mastra/core/memory';
4
+ import type { MemoryStorage } from '@mastra/core/storage';
5
+ import type { ProviderMetadata } from '@mastra/core/stream';
6
+ import type { Memory } from '../../index.js';
7
+ import type { Extractor } from './extractor.js';
8
+ import type { ModelByInputTokens } from './model-by-input-tokens.js';
9
+ /**
10
+ * Threshold can be a simple number or a dynamic range.
11
+ *
12
+ * Simple form:
13
+ * ```ts
14
+ * messageTokens: 10_000
15
+ * ```
16
+ *
17
+ * Range form (dynamic threshold based on observation space):
18
+ * ```ts
19
+ * messageTokens: { min: 8_000, max: 15_000 }
20
+ * ```
21
+ */
22
+ export type ThresholdRange = {
23
+ /** Minimum threshold (used when observations are full) */
24
+ min: number;
25
+ /** Maximum threshold (used when observations have room) */
26
+ max: number;
27
+ };
28
+ /**
29
+ * Model settings for Observer/Reflector agents.
30
+ * Re-exported from @mastra/core/memory for convenience.
31
+ */
32
+ export type ModelSettings = ObservationalMemoryModelSettings;
33
+ /**
34
+ * Google-specific provider options
35
+ */
36
+ export interface GoogleProviderOptions {
37
+ thinkingConfig?: {
38
+ thinkingBudget?: number;
39
+ includeThoughts?: boolean;
40
+ };
41
+ [key: string]: any;
42
+ }
43
+ /**
44
+ * Provider-specific options for model configuration.
45
+ * Compatible with core's ProviderOptions type.
46
+ */
47
+ export interface ProviderOptions {
48
+ google?: GoogleProviderOptions;
49
+ [key: string]: Record<string, any> | undefined;
50
+ }
51
+ export type ActivationTTL = number | string | 'auto' | false;
52
+ export type ResolvedActivationTTL = number | 'auto';
53
+ /**
54
+ * Configuration for the observation step (Observer agent).
55
+ */
56
+ export type ObservationalMemoryModel = Exclude<AgentConfig['model'], undefined> | ModelByInputTokens;
57
+ export interface ObservationConfig {
58
+ /**
59
+ * Model for the Observer agent.
60
+ * Can be a model ID string (e.g., 'openai/gpt-4o'), a LanguageModel instance,
61
+ * a function that returns either (for dynamic model selection),
62
+ * a `ModelByInputTokens` selector (for token-tiered routing),
63
+ * or an array of ModelWithRetries for fallback support.
64
+ *
65
+ * Cannot be set if a top-level `model` is also provided on ObservationalMemoryConfig.
66
+ *
67
+ * @default 'google/gemini-2.5-flash'
68
+ */
69
+ model?: ObservationalMemoryModel;
70
+ /**
71
+ * Token count of unobserved messages that triggers observation.
72
+ * When unobserved message tokens exceed this, the Observer is called.
73
+ *
74
+ * @default 30000
75
+ */
76
+ messageTokens?: number;
77
+ /**
78
+ * Model settings for the Observer agent.
79
+ * @default { temperature: 0.3 }
80
+ *
81
+ * Note: `maxOutputTokens: 100_000` is only applied by default when using
82
+ * the built-in default model selection.
83
+ */
84
+ modelSettings?: ModelSettings;
85
+ /**
86
+ * Provider-specific options.
87
+ * @default { google: { thinkingConfig: { thinkingBudget: 215 } } }
88
+ */
89
+ providerOptions?: ProviderOptions;
90
+ /**
91
+ * Maximum tokens per batch when observing multiple threads.
92
+ * Threads are chunked into batches of this size and processed in parallel.
93
+ * Lower values = more parallelism but more API calls.
94
+ * Higher values = fewer API calls but less parallelism.
95
+ *
96
+ * @default 10000
97
+ */
98
+ maxTokensPerBatch?: number;
99
+ /**
100
+ * Token interval for async background observation buffering.
101
+ * Can be an absolute token count (e.g. `5000`) or a fraction of `messageTokens`
102
+ * (e.g. `0.25` = buffer every 25% of threshold).
103
+ *
104
+ * Observations run asynchronously in the background at this interval,
105
+ * storing results in a buffer. When the main `messageTokens` threshold is reached,
106
+ * buffered observations are activated instantly (no blocking LLM call).
107
+ *
108
+ * Set to `false` to explicitly disable async buffering.
109
+ *
110
+ * Must resolve to less than `messageTokens`.
111
+ *
112
+ * @default 0.2 (buffer every 20% of messageTokens)
113
+ */
114
+ bufferTokens?: number | false;
115
+ /**
116
+ * Whether to run background observation buffering when a turn ends and the agent becomes idle.
117
+ *
118
+ * This is separate from `bufferTokens`: `bufferTokens` controls step-time async buffering,
119
+ * while `bufferOnIdle` controls end-of-turn buffering for short idle turns.
120
+ *
121
+ * @default false
122
+ */
123
+ bufferOnIdle?: boolean;
124
+ /**
125
+ * Controls how many raw message tokens to retain after activation.
126
+ *
127
+ * - **Ratio (0 < value <= 1):** fraction of `messageTokens` to activate.
128
+ * The retention floor is `messageTokens * (1 - ratio)`.
129
+ * e.g. `0.8` with `messageTokens: 30000` → retain ~6000 tokens.
130
+ *
131
+ * - **Absolute (value >= 1000):** exact number of message tokens to retain.
132
+ * e.g. `3000` → always aim to keep ~3000 tokens of raw message history.
133
+ * Must be less than `messageTokens`.
134
+ *
135
+ * Values between 1 and 1000 are invalid.
136
+ *
137
+ * Requires `bufferTokens` to also be set.
138
+ *
139
+ * @default 0.8 (retain ~20% of messageTokens as raw messages)
140
+ */
141
+ bufferActivation?: number;
142
+ /**
143
+ * Time before buffered observations are force-activated after inactivity.
144
+ * Accepts milliseconds as a number, a duration string like `"5m"` or `"1hr"`,
145
+ * or `false` to disable top-level `activateAfterIdle` for observations.
146
+ * If unset, top-level `activateAfterIdle` is used for observations.
147
+ */
148
+ activateAfterIdle?: ActivationTTL;
149
+ /**
150
+ * Force-activate buffered observations when the actor provider/model changes.
151
+ * If unset, top-level `activateOnProviderChange` is used for observations.
152
+ */
153
+ activateOnProviderChange?: boolean;
154
+ /**
155
+ * Token threshold above which synchronous (blocking) observation is forced.
156
+ * Between `messageTokens` and `blockAfter`, only async buffering/activation is used.
157
+ * Above `blockAfter`, a synchronous observation runs as a last resort.
158
+ *
159
+ * Accepts either:
160
+ * - A multiplier (1 < value < 2): multiplied by `messageTokens`.
161
+ * e.g. `blockAfter: 1.5` with `messageTokens: 20_000` → blocks at 30,000.
162
+ * - An absolute token count (≥ 2): must be greater than `messageTokens`.
163
+ *
164
+ * Only relevant when `bufferTokens` is set.
165
+ * If not set, synchronous observation is never used when async buffering is enabled.
166
+ */
167
+ blockAfter?: number;
168
+ /**
169
+ * Optional token budget for observer context.
170
+ * When set, "Previous Observations" is tail-truncated to preserve the most recent entries,
171
+ * and pending buffered reflections replace the raw observations they summarized.
172
+ * Set to `0` for full truncation (omit previous observations entirely), or `false` to disable.
173
+ */
174
+ previousObserverTokens?: number | false;
175
+ /**
176
+ * Custom instructions to append to the Observer's system prompt.
177
+ * Use this to customize observation behavior for specific use cases.
178
+ */
179
+ instruction?: string;
180
+ /**
181
+ * Manage working memory through Observational Memory extraction.
182
+ * When enabled alongside `workingMemory.enabled`, Memory supplies defaults that
183
+ * disable main-agent working memory management and add the WorkingMemoryExtractor.
184
+ * Set `workingMemory.agentManaged: true` to keep main-agent tools/instructions enabled.
185
+ *
186
+ * @default false
187
+ */
188
+ manageWorkingMemory?: boolean;
189
+ /**
190
+ * Additional values to extract from observer output. Built-in OM fields are registered automatically.
191
+ * @experimental Extractors are experimental and may change in a future release.
192
+ */
193
+ extract?: Extractor<any>[];
194
+ /**
195
+ * Whether the Observer should suggest thread titles.
196
+ * When enabled, the Observer will analyze conversation context and
197
+ * suggest a short, descriptive title for the thread.
198
+ *
199
+ * @default false
200
+ */
201
+ threadTitle?: boolean;
202
+ /**
203
+ * Controls which attachment parts (image/file) are forwarded to the
204
+ * Observer model alongside their placeholder text lines. The placeholder
205
+ * line (e.g. `[Image #1: photo.png]`) is always emitted so the Observer
206
+ * still knows an attachment existed.
207
+ *
208
+ * - `'auto'`: use the provider capabilities registry to decide.
209
+ * If the observer model supports attachments (multimodal input), they
210
+ * are forwarded; otherwise they are dropped. Falls back to `true` when
211
+ * no capabilities data is available for the model.
212
+ * - `true`: forward all attachments.
213
+ * - `false`: drop all attachments; placeholders remain visible.
214
+ * - `string[]`: allowlist of mimeType patterns. Each entry is matched
215
+ * case-insensitively against the part's mimeType. Supports exact matches
216
+ * (`'application/pdf'`), wildcard subtypes (`'image/*'`), and bare `'*'`
217
+ * for everything. An empty array drops everything.
218
+ *
219
+ * Use this when the Observer model is text-only (e.g. some DeepSeek
220
+ * endpoints) while the main agent uses a multimodal model. The same
221
+ * filter applies to tool results that contain image or file parts.
222
+ *
223
+ * @default true
224
+ */
225
+ observeAttachments?: 'auto' | boolean | string[];
226
+ }
227
+ /**
228
+ * Configuration for the reflection step (Reflector agent).
229
+ */
230
+ export interface ReflectionConfig {
231
+ /**
232
+ * Model for the Reflector agent.
233
+ * Can be a model ID string (e.g., 'openai/gpt-4o'), a LanguageModel instance,
234
+ * a function that returns either (for dynamic model selection),
235
+ * a `ModelByInputTokens` selector (for token-tiered routing),
236
+ * or an array of ModelWithRetries for fallback support.
237
+ *
238
+ * Cannot be set if a top-level `model` is also provided on ObservationalMemoryConfig.
239
+ *
240
+ * @default 'google/gemini-2.5-flash'
241
+ */
242
+ model?: ObservationalMemoryModel;
243
+ /**
244
+ * Token count of observations that triggers reflection.
245
+ * When observation tokens exceed this, the Reflector is called to condense them.
246
+ *
247
+ * @default 40000
248
+ */
249
+ observationTokens?: number;
250
+ /**
251
+ * Model settings for the Reflector agent.
252
+ * @default { temperature: 0 }
253
+ *
254
+ * Note: `maxOutputTokens: 100_000` is only applied by default when using
255
+ * the built-in default model selection.
256
+ */
257
+ modelSettings?: ModelSettings;
258
+ /**
259
+ * Provider-specific options.
260
+ * @default { google: { thinkingConfig: { thinkingBudget: 1024 } } }
261
+ */
262
+ providerOptions?: ProviderOptions;
263
+ /**
264
+ * Token threshold above which synchronous (blocking) reflection is forced.
265
+ * Between `observationTokens` and `blockAfter`, only async buffering/activation is used.
266
+ * Above `blockAfter`, a synchronous reflection runs as a last resort.
267
+ *
268
+ * Accepts either:
269
+ * - A multiplier (1 < value < 2): multiplied by `observationTokens`.
270
+ * e.g. `blockAfter: 1.5` with `observationTokens: 30_000` → blocks at 45,000.
271
+ * - An absolute token count (≥ 2): must be greater than `observationTokens`.
272
+ *
273
+ * Only relevant when `bufferActivation` is set.
274
+ * If not set, synchronous reflection is never used when async reflection is enabled.
275
+ */
276
+ blockAfter?: number;
277
+ /**
278
+ * Time before buffered reflections are force-activated after inactivity.
279
+ * Accepts milliseconds as a number, a duration string like `"5m"` or `"1hr"`,
280
+ * or `false` to disable idle activation for reflections.
281
+ * Reflections do not inherit top-level `activateAfterIdle`; set this explicitly to enable.
282
+ */
283
+ activateAfterIdle?: ActivationTTL;
284
+ /**
285
+ * Force-activate buffered reflections when the actor provider/model changes.
286
+ * Reflections do not inherit top-level `activateOnProviderChange`; set this explicitly to enable.
287
+ */
288
+ activateOnProviderChange?: boolean;
289
+ /**
290
+ * Ratio (0-1) controlling when async reflection buffering starts.
291
+ * When observation tokens reach `observationTokens * bufferActivation`,
292
+ * reflection runs in the background. On activation at the full threshold,
293
+ * the buffered reflection replaces the line range it covers, preserving
294
+ * any new observations appended after that range.
295
+ *
296
+ * Requires `observation.bufferTokens` to also be set.
297
+ */
298
+ bufferActivation?: number;
299
+ /**
300
+ * Custom instructions to append to the Reflector's system prompt.
301
+ * Use this to customize reflection behavior for specific use cases.
302
+ */
303
+ instruction?: string;
304
+ /**
305
+ * Additional values to extract from reflector output. Built-in OM fields are registered automatically.
306
+ * @experimental Extractors are experimental and may change in a future release.
307
+ */
308
+ extract?: Extractor<any>[];
309
+ }
310
+ /**
311
+ * Result from Observer agent
312
+ */
313
+ export interface ObserverResult {
314
+ /** The extracted observations */
315
+ observations: string;
316
+ /** Suggested continuation for the Actor */
317
+ suggestedContinuation?: string;
318
+ /** Extracted values keyed by extractor slug */
319
+ extractedValues?: Record<string, unknown>;
320
+ /** Extractor failures keyed by extractor slug */
321
+ extractionFailures?: Array<{
322
+ slug: string;
323
+ error: string;
324
+ }>;
325
+ }
326
+ /**
327
+ * Result from Reflector agent
328
+ */
329
+ export interface ReflectorResult {
330
+ /** The condensed observations */
331
+ observations: string;
332
+ /** Suggested continuation for the Actor */
333
+ suggestedContinuation?: string;
334
+ /** True if the output was detected as degenerate (repetition loop) and should be discarded/retried */
335
+ degenerate?: boolean;
336
+ /** Extracted values keyed by extractor slug */
337
+ extractedValues?: Record<string, unknown>;
338
+ /** Extractor failures keyed by extractor slug */
339
+ extractionFailures?: Array<{
340
+ slug: string;
341
+ error: string;
342
+ }>;
343
+ }
344
+ /**
345
+ * Config snapshot included in observation markers for debugging.
346
+ */
347
+ export interface ObservationMarkerConfig {
348
+ messageTokens: number;
349
+ observationTokens: number;
350
+ scope: 'thread' | 'resource';
351
+ activateAfterIdle?: ResolvedActivationTTL;
352
+ }
353
+ export interface ObservationModelContext {
354
+ provider?: string;
355
+ modelId?: string;
356
+ providerOptions?: ProviderOptions;
357
+ }
358
+ /**
359
+ * Start marker inserted when observation begins.
360
+ * Everything BEFORE this marker will be observed.
361
+ *
362
+ * If this marker exists without a corresponding `end` or `failed` marker,
363
+ * observation is in progress.
364
+ */
365
+ /** Type of OM operation - observation or reflection */
366
+ export type OmOperationType = 'observation' | 'reflection';
367
+ export interface DataOmObservationStartPart {
368
+ type: 'data-om-observation-start';
369
+ data: {
370
+ /** Unique ID for this observation cycle - shared between start/end/failed markers */
371
+ cycleId: string;
372
+ /** Type of operation: 'observation' or 'reflection' */
373
+ operationType: OmOperationType;
374
+ /** When observation started */
375
+ startedAt: string;
376
+ /** Tokens being observed in this batch */
377
+ tokensToObserve: number;
378
+ /** The OM record ID this observation belongs to */
379
+ recordId: string;
380
+ /** This thread's ID */
381
+ threadId: string;
382
+ /** All thread IDs being observed in this batch (for resource-scoped) */
383
+ threadIds: string[];
384
+ /** Snapshot of config at observation time */
385
+ config: ObservationMarkerConfig;
386
+ };
387
+ }
388
+ /**
389
+ * End marker inserted when observation completes successfully.
390
+ * Parts BEFORE the corresponding `start` marker have been observed.
391
+ */
392
+ export interface DataOmObservationEndPart {
393
+ type: 'data-om-observation-end';
394
+ data: {
395
+ /** Unique ID for this observation cycle - shared between start/end/failed markers */
396
+ cycleId: string;
397
+ /** Type of operation: 'observation' or 'reflection' */
398
+ operationType: OmOperationType;
399
+ /** When observation completed */
400
+ completedAt: string;
401
+ /** Duration in milliseconds */
402
+ durationMs: number;
403
+ /** Total tokens that were observed */
404
+ tokensObserved: number;
405
+ /** Resulting observation tokens after compression */
406
+ observationTokens: number;
407
+ /** The actual observations generated in this cycle */
408
+ observations?: string;
409
+ /** Current task extracted by the Observer */
410
+ currentTask?: string;
411
+ /** Suggested response extracted by the Observer */
412
+ suggestedResponse?: string;
413
+ /** Extracted values keyed by extractor slug */
414
+ extractedValues?: Record<string, unknown>;
415
+ /** Extractor failures keyed by extractor slug */
416
+ extractionFailures?: Array<{
417
+ slug: string;
418
+ error: string;
419
+ }>;
420
+ /** The OM record ID */
421
+ recordId: string;
422
+ /** This thread's ID */
423
+ threadId: string;
424
+ };
425
+ }
426
+ /**
427
+ * Failed marker inserted when observation fails.
428
+ * Allows for retry logic and debugging.
429
+ */
430
+ export interface DataOmObservationFailedPart {
431
+ type: 'data-om-observation-failed';
432
+ data: {
433
+ /** Unique ID for this observation cycle - shared between start/end/failed markers */
434
+ cycleId: string;
435
+ /** Type of operation: 'observation' or 'reflection' */
436
+ operationType: OmOperationType;
437
+ /** When observation failed */
438
+ failedAt: string;
439
+ /** Duration until failure in milliseconds */
440
+ durationMs: number;
441
+ /** Tokens that were attempted to observe */
442
+ tokensAttempted: number;
443
+ /** Error message */
444
+ error: string;
445
+ /** The OM record ID */
446
+ recordId: string;
447
+ /** This thread's ID */
448
+ threadId: string;
449
+ /** The buffered observations/reflection content (for UI expansion) */
450
+ observations?: string;
451
+ };
452
+ }
453
+ /**
454
+ * Status update streamed during agent execution to provide real-time
455
+ * observational memory state for UI feedback.
456
+ *
457
+ * Clients can calculate percentages from tokens/threshold pairs.
458
+ *
459
+ * @example
460
+ * ```ts
461
+ * // Message window usage
462
+ * const msgPercent = status.windows.active.messages.tokens / status.windows.active.messages.threshold;
463
+ *
464
+ * // Post-activation estimate for message window
465
+ * const postActivation = status.windows.active.messages.tokens - status.windows.buffered.observations.messageTokens;
466
+ * ```
467
+ */
468
+ export interface DataOmStatusPart {
469
+ type: 'data-om-status';
470
+ data: {
471
+ windows: {
472
+ /** Active context windows — current token usage and thresholds */
473
+ active: {
474
+ /** Message window: unobserved message tokens vs threshold that triggers observation */
475
+ messages: {
476
+ tokens: number;
477
+ threshold: number;
478
+ };
479
+ /** Observation window: observation tokens vs threshold that triggers reflection */
480
+ observations: {
481
+ tokens: number;
482
+ threshold: number;
483
+ };
484
+ };
485
+ /** Buffered content waiting to be activated */
486
+ buffered: {
487
+ /** Buffered observation chunks staged for activation */
488
+ observations: {
489
+ /** Number of chunks staged */
490
+ chunks: number;
491
+ /** Message tokens that will be cleared from context on activation */
492
+ messageTokens: number;
493
+ /** Projected message tokens that would be removed if activation happened now (based on bufferActivation ratio and chunk boundaries) */
494
+ projectedMessageRemoval: number;
495
+ /** Observation tokens that will be added on activation */
496
+ observationTokens: number;
497
+ /** Current state of observation buffering */
498
+ status: 'idle' | 'running' | 'complete';
499
+ };
500
+ /** Buffered reflection waiting to be activated */
501
+ reflection: {
502
+ /** Observation tokens that were fed into the reflector (pre-compression) */
503
+ inputObservationTokens: number;
504
+ /** Observation tokens the reflection will produce on activation (post-compression) */
505
+ observationTokens: number;
506
+ /** Current state of reflection buffering */
507
+ status: 'idle' | 'running' | 'complete';
508
+ };
509
+ };
510
+ };
511
+ /** The OM record ID */
512
+ recordId: string;
513
+ /** Thread ID */
514
+ threadId: string;
515
+ /** Step number in the agent loop */
516
+ stepNumber: number;
517
+ /** Current reflection generation count */
518
+ generationCount: number;
519
+ };
520
+ }
521
+ /**
522
+ * Start marker inserted when async buffering begins.
523
+ * Buffering runs in the background to pre-compute observations before the main threshold.
524
+ */
525
+ export interface DataOmBufferingStartPart {
526
+ type: 'data-om-buffering-start';
527
+ data: {
528
+ /** Unique ID for this buffering cycle - shared between start/end/failed markers */
529
+ cycleId: string;
530
+ /** Type of operation being buffered: 'observation' or 'reflection' */
531
+ operationType: OmOperationType;
532
+ /** When buffering started */
533
+ startedAt: string;
534
+ /** Tokens being buffered in this cycle */
535
+ tokensToBuffer: number;
536
+ /** The OM record ID this buffering belongs to */
537
+ recordId: string;
538
+ /** This thread's ID */
539
+ threadId: string;
540
+ /** All thread IDs being buffered (for resource-scoped) */
541
+ threadIds: string[];
542
+ /** Snapshot of config at buffering time */
543
+ config: ObservationMarkerConfig;
544
+ };
545
+ }
546
+ /**
547
+ * End marker inserted when async buffering completes successfully.
548
+ * The buffered content is stored but not yet activated (visible to the main context).
549
+ */
550
+ export interface DataOmBufferingEndPart {
551
+ type: 'data-om-buffering-end';
552
+ data: {
553
+ /** Unique ID for this buffering cycle - shared between start/end/failed markers */
554
+ cycleId: string;
555
+ /** Type of operation that was buffered: 'observation' or 'reflection' */
556
+ operationType: OmOperationType;
557
+ /** When buffering completed */
558
+ completedAt: string;
559
+ /** Duration in milliseconds */
560
+ durationMs: number;
561
+ /** Total tokens that were buffered */
562
+ tokensBuffered: number;
563
+ /** Resulting observation/reflection tokens after compression */
564
+ bufferedTokens: number;
565
+ /** The OM record ID */
566
+ recordId: string;
567
+ /** This thread's ID */
568
+ threadId: string;
569
+ /** The buffered observations/reflection content (for UI expansion) */
570
+ observations?: string;
571
+ /** Extracted values keyed by extractor slug */
572
+ extractedValues?: Record<string, unknown>;
573
+ /** Extractor failures keyed by extractor slug */
574
+ extractionFailures?: Array<{
575
+ slug: string;
576
+ error: string;
577
+ }>;
578
+ };
579
+ }
580
+ /**
581
+ * Failed marker inserted when async buffering fails.
582
+ * The system will fall back to synchronous processing at threshold.
583
+ */
584
+ export interface DataOmBufferingFailedPart {
585
+ type: 'data-om-buffering-failed';
586
+ data: {
587
+ /** Unique ID for this buffering cycle - shared between start/end/failed markers */
588
+ cycleId: string;
589
+ /** Type of operation that failed: 'observation' or 'reflection' */
590
+ operationType: OmOperationType;
591
+ /** When buffering failed */
592
+ failedAt: string;
593
+ /** Duration until failure in milliseconds */
594
+ durationMs: number;
595
+ /** Tokens that were attempted to buffer */
596
+ tokensAttempted: number;
597
+ /** Error message */
598
+ error: string;
599
+ /** The OM record ID */
600
+ recordId: string;
601
+ /** This thread's ID */
602
+ threadId: string;
603
+ /** The buffered observations/reflection content (for UI expansion) */
604
+ observations?: string;
605
+ };
606
+ }
607
+ /**
608
+ * Union of all buffering marker types.
609
+ */
610
+ export type DataOmBufferingPart = DataOmBufferingStartPart | DataOmBufferingEndPart | DataOmBufferingFailedPart;
611
+ /**
612
+ * Marker inserted when buffered observations are activated (moved to active context).
613
+ * This is an instant operation that happens when the main threshold is reached.
614
+ */
615
+ export interface DataOmActivationPart {
616
+ type: 'data-om-activation';
617
+ data: {
618
+ /** Unique ID for this activation event */
619
+ cycleId: string;
620
+ /** Type of operation: 'observation' or 'reflection' */
621
+ operationType: OmOperationType;
622
+ /** When activation occurred */
623
+ activatedAt: string;
624
+ /** Number of buffered chunks that were activated */
625
+ chunksActivated: number;
626
+ /** Total tokens from messages that were activated */
627
+ tokensActivated: number;
628
+ /** Resulting observation tokens after activation */
629
+ observationTokens: number;
630
+ /** Number of messages that were observed via activation */
631
+ messagesActivated: number;
632
+ /** The OM record ID */
633
+ recordId: string;
634
+ /** This thread's ID */
635
+ threadId: string;
636
+ /** Current reflection generation count */
637
+ generationCount: number;
638
+ /** Snapshot of config at activation time */
639
+ config: ObservationMarkerConfig;
640
+ /** The actual observations from activated chunks (for UI display) */
641
+ observations?: string;
642
+ /** Whether activation was triggered by threshold crossing, activateAfterIdle expiry, or a model/provider change */
643
+ triggeredBy?: 'threshold' | 'ttl' | 'provider_change';
644
+ /** Unix-ms timestamp of the last assistant message part used for TTL checks */
645
+ lastActivityAt?: number;
646
+ /** How long activateAfterIdle had been exceeded when activation fired */
647
+ ttlExpiredMs?: number;
648
+ /** Previous assistant model identifier that triggered activation, e.g. openai/gpt-4o */
649
+ previousModel?: string;
650
+ /** Current actor model identifier that triggered activation, e.g. anthropic/claude-3-7-sonnet */
651
+ currentModel?: string;
652
+ };
653
+ }
654
+ /**
655
+ * Marker emitted when thread title is updated by the observer.
656
+ */
657
+ export interface DataOmThreadUpdatePart {
658
+ type: 'data-om-thread-update';
659
+ data: {
660
+ /** Unique ID for this observation cycle - shared with observation markers */
661
+ cycleId: string;
662
+ /** The thread ID that was updated */
663
+ threadId: string;
664
+ /** The previous thread title (undefined if thread had no title) */
665
+ oldTitle?: string;
666
+ /** The new thread title */
667
+ newTitle: string;
668
+ /** When this update occurred */
669
+ timestamp: string;
670
+ };
671
+ }
672
+ /**
673
+ * Union of all observation marker types.
674
+ */
675
+ export type DataOmObservationPart = DataOmObservationStartPart | DataOmObservationEndPart | DataOmObservationFailedPart | DataOmStatusPart | DataOmThreadUpdatePart;
676
+ /**
677
+ * Union of all OM data parts (observation, buffering, status, activation).
678
+ */
679
+ export type DataOmPart = DataOmObservationPart | DataOmBufferingPart | DataOmActivationPart;
680
+ /**
681
+ * @deprecated Use DataOmObservationStartPart and DataOmObservationEndPart instead.
682
+ * Kept for backwards compatibility during migration.
683
+ */
684
+ export interface DataOmObservedPart {
685
+ type: 'data-om-observed';
686
+ data: {
687
+ /** When this observation occurred */
688
+ observedAt: string;
689
+ /** Total tokens observed across all threads in this batch */
690
+ tokensObserved: number;
691
+ /** Resulting observation tokens after compression */
692
+ observationTokens: number;
693
+ /** The OM record ID this observation belongs to */
694
+ recordId: string;
695
+ /** This thread's ID */
696
+ threadId: string;
697
+ /** All thread IDs that were observed in this batch (for resource-scoped) */
698
+ threadIds: string[];
699
+ /** Snapshot of config at observation time (for debugging) */
700
+ config?: ObservationMarkerConfig;
701
+ };
702
+ }
703
+ /**
704
+ * Debug event emitted when observation-related events occur.
705
+ * Useful for understanding what the Observer is doing.
706
+ */
707
+ export interface ObservationDebugEvent {
708
+ type: 'observation_triggered' | 'observation_complete' | 'reflection_triggered' | 'reflection_complete' | 'tokens_accumulated' | 'step_progress';
709
+ timestamp: Date;
710
+ threadId: string;
711
+ resourceId: string;
712
+ /** Messages that were sent to the Observer */
713
+ messages?: Array<{
714
+ role: string;
715
+ content: string;
716
+ }>;
717
+ /** Token counts */
718
+ pendingTokens?: number;
719
+ sessionTokens?: number;
720
+ totalPendingTokens?: number;
721
+ threshold?: number;
722
+ /** Input token count (for reflection events) */
723
+ inputTokens?: number;
724
+ /** Number of active observations (for reflection events) */
725
+ activeObservationsLength?: number;
726
+ /** Output token count after reflection */
727
+ outputTokens?: number;
728
+ /** The observations that were generated */
729
+ observations?: string;
730
+ /** Previous observations (before this event) */
731
+ previousObservations?: string;
732
+ /** Observer's raw output */
733
+ rawObserverOutput?: string;
734
+ /** LLM usage from Observer/Reflector calls */
735
+ usage?: {
736
+ inputTokens?: number;
737
+ outputTokens?: number;
738
+ totalTokens?: number;
739
+ };
740
+ /** Step progress fields (for step_progress events) */
741
+ stepNumber?: number;
742
+ finishReason?: string;
743
+ thresholdPercent?: number;
744
+ willSave?: boolean;
745
+ willObserve?: boolean;
746
+ }
747
+ /**
748
+ * Configuration for ObservationalMemory
749
+ */
750
+ export interface ObservationalMemoryConfig {
751
+ /**
752
+ * Storage adapter for persisting observations.
753
+ * Must be a MemoryStorage instance (from MastraStorage.stores.memory).
754
+ */
755
+ storage: MemoryStorage;
756
+ /** Active Memory instance, when Observational Memory is created by Memory. */
757
+ memory?: Memory;
758
+ /**
759
+ * Enable retrieval-mode observation group metadata.
760
+ * When true, observation groups are treated as durable pointers to raw
761
+ * message history and a `recall` tool is registered so the actor can
762
+ * inspect raw messages behind a stored observation summary.
763
+ *
764
+ * Use `{ vector: true }` to also index emitted observation groups into the
765
+ * configured vector store for semantic recall, and `scope` to limit recall
766
+ * browsing to the current thread instead of the whole resource.
767
+ *
768
+ * Use `instructions` to append application-specific recall guidance after
769
+ * Mastra's built-in retrieval instructions. The built-in instructions are
770
+ * never replaced.
771
+ *
772
+ * @default false
773
+ */
774
+ retrieval?: boolean | {
775
+ vector?: boolean;
776
+ scope?: 'thread' | 'resource';
777
+ instructions?: string;
778
+ };
779
+ /**
780
+ * Optional callback used to index emitted observation groups for semantic retrieval.
781
+ */
782
+ onIndexObservations?: (observation: {
783
+ text: string;
784
+ groupId: string;
785
+ range: string;
786
+ threadId: string;
787
+ resourceId: string;
788
+ observedAt?: Date;
789
+ }) => Promise<void>;
790
+ /**
791
+ * Model for both Observer and Reflector agents.
792
+ * Sets the model for both agents at once. Cannot be used together with
793
+ * `observation.model` or `reflection.model` — an error will be thrown.
794
+ *
795
+ * @default 'google/gemini-2.5-flash'
796
+ */
797
+ model?: ObservationalMemoryModel;
798
+ /**
799
+ * Observation step configuration.
800
+ */
801
+ observation?: ObservationConfig;
802
+ /**
803
+ * Reflection step configuration.
804
+ */
805
+ reflection?: ReflectionConfig;
806
+ /**
807
+ * Memory scope for observations.
808
+ * - 'resource': Observations span all threads for a resource (cross-thread memory)
809
+ * - 'thread': Observations are per-thread (default)
810
+ */
811
+ scope?: 'resource' | 'thread';
812
+ /**
813
+ * Debug callback for observation events.
814
+ * Called whenever observation-related events occur.
815
+ * Useful for debugging and understanding the observation flow.
816
+ */
817
+ onDebugEvent?: (event: ObservationDebugEvent) => void;
818
+ /**
819
+ * Lifecycle hooks fired for every observation/reflection cycle: the manual
820
+ * APIs (`observe()` / `reflect()`), turn-engine sync observation, and
821
+ * fire-and-forget async buffering — the automatic paths that per-call
822
+ * `observe()` hooks never see. Callbacks receive `threadId` / `resourceId`
823
+ * / `trigger` context, plus `usage` and `providerMetadata` on cycle end,
824
+ * so consumers can account for OM model economics without wrapping the
825
+ * observer/reflector models in middleware.
826
+ *
827
+ * Semantics worth knowing:
828
+ * - Failed async-buffer cycles never throw (fire-and-forget), so the
829
+ * failure is reported via the end hook's `error` field instead.
830
+ * - An end hook may fire with neither `usage` nor `error` when a cycle
831
+ * concludes without a model call (e.g. a concurrent-observation
832
+ * stale-record check skips the work).
833
+ * - Errors thrown (or promise rejections returned) by these hooks are
834
+ * caught and logged at OM debug level (`OM_DEBUG`); they never fail the
835
+ * cycle.
836
+ */
837
+ hooks?: ObserveHooks;
838
+ obscureThreadIds?: boolean;
839
+ /**
840
+ * Share the token budget between messages and observations.
841
+ * When true, the total budget = observation.messageTokens + reflection.observationTokens.
842
+ * - Messages can use more space when observations are small
843
+ * - Observations can use more space when messages are small
844
+ *
845
+ * This helps maximize context usage by allowing flexible allocation.
846
+ *
847
+ * @default false
848
+ */
849
+ shareTokenBudget?: boolean;
850
+ /**
851
+ * When true, inserts temporal-gap reminder markers before new user messages after
852
+ * significant inactivity.
853
+ *
854
+ * @default false
855
+ */
856
+ temporalMarkers?: boolean;
857
+ /**
858
+ * Time before buffered observations are force-activated after inactivity.
859
+ * Accepts milliseconds as a number or a duration string like `"5m"` or `"1hr"`.
860
+ * When the gap between the current time and the last assistant message part's `createdAt`
861
+ * exceeds this value, buffered observations activate regardless of whether the
862
+ * token threshold has been reached.
863
+ *
864
+ * Reflections do not inherit this setting. Use `reflection.activateAfterIdle` to
865
+ * opt reflections into idle activation.
866
+ */
867
+ activateAfterIdle?: ActivationTTL;
868
+ /**
869
+ * Force-activate buffered observations when the actor provider/model changes.
870
+ * This helps flush prompt-cache-specific memory before switching to a different model.
871
+ *
872
+ * Reflections do not inherit this setting. Use `reflection.activateOnProviderChange`
873
+ * to opt reflections into provider-change activation.
874
+ */
875
+ activateOnProviderChange?: boolean;
876
+ /** @internal Parent Mastra instance for custom gateway model resolution. */
877
+ mastra?: Mastra;
878
+ }
879
+ /**
880
+ * Internal resolved config with all defaults applied.
881
+ * Thresholds are stored as ThresholdRange internally for dynamic calculation,
882
+ * even when user provides a simple number (converted based on shareTokenBudget).
883
+ */
884
+ export interface ResolvedObservationConfig {
885
+ model: ObservationalMemoryModel;
886
+ /** Internal threshold - always stored as ThresholdRange for dynamic calculation */
887
+ messageTokens: number | ThresholdRange;
888
+ /** Whether shared token budget is enabled */
889
+ shareTokenBudget: boolean;
890
+ /** Model settings - merged with user config and defaults */
891
+ modelSettings: ModelSettings;
892
+ providerOptions: ProviderOptions;
893
+ maxTokensPerBatch: number;
894
+ /** Token interval for async background observation buffering (resolved from config) */
895
+ bufferTokens?: number;
896
+ /** Whether to buffer unobserved messages at the end of an idle turn */
897
+ bufferOnIdle: boolean;
898
+ /** Ratio of buffered observations to activate (0-1 float) */
899
+ bufferActivation?: number;
900
+ /** Time in milliseconds, or auto provider-aware TTL, before buffered observations are force-activated based on the last assistant message part timestamp */
901
+ activateAfterIdle?: ResolvedActivationTTL;
902
+ /** Force-activate buffered observations when the actor model/provider changes */
903
+ activateOnProviderChange?: boolean;
904
+ /** Token threshold above which synchronous observation is forced */
905
+ blockAfter?: number;
906
+ /** Optional token budget for observer context optimization (0 = full truncation, false = disabled) */
907
+ previousObserverTokens?: number | false;
908
+ /** Custom instructions to append to the Observer's system prompt */
909
+ instruction?: string;
910
+ /** Whether the Observer should suggest thread titles */
911
+ threadTitle?: boolean;
912
+ /** Filter for attachment parts forwarded to the Observer model */
913
+ observeAttachments: 'auto' | boolean | string[];
914
+ /** Resolved observer extractors, including enabled built-ins and user extractors */
915
+ extractors: Extractor<any>[];
916
+ }
917
+ export interface ResolvedReflectionConfig {
918
+ model: ObservationalMemoryModel;
919
+ /** Internal threshold - always stored as ThresholdRange for dynamic calculation */
920
+ observationTokens: number | ThresholdRange;
921
+ /** Whether shared token budget is enabled */
922
+ shareTokenBudget: boolean;
923
+ /** Model settings - merged with user config and defaults */
924
+ modelSettings: ModelSettings;
925
+ providerOptions: ProviderOptions;
926
+ /** Ratio (0-1) controlling when async reflection buffering starts */
927
+ bufferActivation?: number;
928
+ /** Time in milliseconds, or auto provider-aware TTL, before buffered reflections are force-activated based on the last assistant message part timestamp */
929
+ activateAfterIdle?: ResolvedActivationTTL;
930
+ /** Force-activate buffered reflections when the actor model/provider changes */
931
+ activateOnProviderChange?: boolean;
932
+ /** Token threshold above which synchronous reflection is forced */
933
+ blockAfter?: number;
934
+ /** Custom instructions to append to the Reflector's system prompt */
935
+ instruction?: string;
936
+ /** Resolved reflector extractors, including enabled built-ins and user extractors */
937
+ extractors: Extractor<any>[];
938
+ }
939
+ export interface ObserveHookUsage {
940
+ inputTokens?: number;
941
+ outputTokens?: number;
942
+ totalTokens?: number;
943
+ }
944
+ /**
945
+ * Which pipeline path INITIATED the observation/reflection cycle a hook fires
946
+ * for — not whether the cycle itself ran synchronously:
947
+ * - 'manual': direct API calls (`observe()`, `reflect()`).
948
+ * - 'turn-sync': the observation turn engine's synchronous lane, including
949
+ * reflections it initiates (even when those buffer asynchronously).
950
+ * - 'async-buffer': the buffered-observation lane (`buffer()` /
951
+ * `triggerAsyncBuffering`), whether awaited or fire-and-forget.
952
+ */
953
+ export type ObserveTrigger = 'manual' | 'turn-sync' | 'async-buffer';
954
+ /**
955
+ * Call context passed to config-level `ObserveHooks` callbacks. Config-level
956
+ * hooks are shared across all threads/resources of an ObservationalMemory
957
+ * instance, so every invocation carries the identifiers of the cycle it fires
958
+ * for. Per-call `observe()` hooks do not receive these fields — the caller
959
+ * already knows its own thread.
960
+ */
961
+ export interface ObserveHookContext {
962
+ threadId?: string;
963
+ resourceId?: string;
964
+ trigger?: ObserveTrigger;
965
+ }
966
+ export interface ObserveHooks {
967
+ onObservationStart?: (info?: ObserveHookContext) => void;
968
+ /**
969
+ * Fires when an observation cycle ends. `providerMetadata` carries the OM
970
+ * observer model call's full provider metadata (e.g. AI Gateway cost and
971
+ * generation id under `providerMetadata.gateway`); it is undefined when the
972
+ * provider emits none. For batched resource-scoped observations it reflects
973
+ * the last batch that emitted provider metadata (per-call values are not
974
+ * summed/merged). The `ObserveHookContext` fields are populated for
975
+ * config-level hooks only.
976
+ */
977
+ onObservationEnd?: (result: {
978
+ usage?: ObserveHookUsage;
979
+ error?: Error;
980
+ providerMetadata?: ProviderMetadata;
981
+ } & ObserveHookContext) => void;
982
+ onReflectionStart?: (info?: ObserveHookContext) => void;
983
+ /**
984
+ * Fires when a reflection cycle ends. `providerMetadata` carries the OM
985
+ * reflector model call's full provider metadata; it is undefined when the
986
+ * provider emits none. Across retry attempts `usage` is summed but
987
+ * `providerMetadata` reflects the last attempt that emitted it (per-call
988
+ * values are not merged). The `ObserveHookContext` fields are populated for
989
+ * config-level hooks only.
990
+ */
991
+ onReflectionEnd?: (result: {
992
+ usage?: ObserveHookUsage;
993
+ error?: Error;
994
+ providerMetadata?: ProviderMetadata;
995
+ } & ObserveHookContext) => void;
996
+ }
997
+ //# sourceMappingURL=types.d.ts.map