@mastra/memory 1.28.3 → 1.29.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/docs/SKILL.md +1 -1
  2. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  3. package/dist/docs/references/docs-memory-message-history.md +1 -1
  4. package/dist/docs/references/docs-memory-multi-user-threads.md +1 -1
  5. package/dist/docs/references/docs-memory-observational-memory.md +41 -1
  6. package/dist/docs/references/docs-memory-overview.md +4 -4
  7. package/dist/docs/references/reference-memory-observational-memory.md +1 -1
  8. package/dist/index.cjs +1 -1
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +1 -1
  11. package/dist/processors/index.cjs +1 -1
  12. package/dist/processors/index.js +1 -1
  13. package/dist/processors/observational-memory/error.d.ts +3 -0
  14. package/dist/processors/observational-memory/error.d.ts.map +1 -0
  15. package/dist/processors/observational-memory/index.d.ts +1 -1
  16. package/dist/processors/observational-memory/index.d.ts.map +1 -1
  17. package/dist/processors/observational-memory/markers.d.ts +2 -2
  18. package/dist/processors/observational-memory/markers.d.ts.map +1 -1
  19. package/dist/processors/observational-memory/observation-strategies/async-buffer.d.ts.map +1 -1
  20. package/dist/processors/observational-memory/observation-strategies/base.d.ts.map +1 -1
  21. package/dist/processors/observational-memory/observation-strategies/resource-scoped.d.ts.map +1 -1
  22. package/dist/processors/observational-memory/observation-strategies/sync.d.ts.map +1 -1
  23. package/dist/processors/observational-memory/observation-strategies/types.d.ts +3 -1
  24. package/dist/processors/observational-memory/observation-strategies/types.d.ts.map +1 -1
  25. package/dist/processors/observational-memory/observation-turn/step.d.ts.map +1 -1
  26. package/dist/processors/observational-memory/observational-memory.d.ts +3 -3
  27. package/dist/processors/observational-memory/observational-memory.d.ts.map +1 -1
  28. package/dist/processors/observational-memory/observer-runner.d.ts +60 -46
  29. package/dist/processors/observational-memory/observer-runner.d.ts.map +1 -1
  30. package/dist/processors/observational-memory/processor.d.ts.map +1 -1
  31. package/dist/processors/observational-memory/reflector-runner.d.ts +5 -1
  32. package/dist/processors/observational-memory/reflector-runner.d.ts.map +1 -1
  33. package/dist/processors/observational-memory/transform-hooks.d.ts +15 -0
  34. package/dist/processors/observational-memory/transform-hooks.d.ts.map +1 -0
  35. package/dist/processors/observational-memory/types.d.ts +71 -2
  36. package/dist/processors/observational-memory/types.d.ts.map +1 -1
  37. package/dist/{src-BFP4tRqs.js → src-BNB8ko_o.js} +193 -45
  38. package/dist/src-BNB8ko_o.js.map +1 -0
  39. package/dist/{src-D4Wm6M4v.cjs → src-DjCR8GJe.cjs} +193 -45
  40. package/dist/src-DjCR8GJe.cjs.map +1 -0
  41. package/package.json +4 -4
  42. package/dist/src-BFP4tRqs.js.map +0 -1
  43. package/dist/src-D4Wm6M4v.cjs.map +0 -1
@@ -18892,11 +18892,11 @@ function formatObserverAttachmentPlaceholder(part, counter) {
18892
18892
  const label = resolveObserverAttachmentLabel(part);
18893
18893
  return label ? `[${attachmentType} #${attachmentId}: ${label}]` : `[${attachmentType} #${attachmentId}]`;
18894
18894
  }
18895
- function isRecord$3(value) {
18895
+ function isRecord$4(value) {
18896
18896
  return !!value && typeof value === "object";
18897
18897
  }
18898
18898
  function mapToolResultBlockToAttachment(block) {
18899
- if (!isRecord$3(block) || typeof block.type !== "string") return;
18899
+ if (!isRecord$4(block) || typeof block.type !== "string") return;
18900
18900
  const mediaType = typeof block.mediaType === "string" ? block.mediaType : void 0;
18901
18901
  const filename = typeof block.filename === "string" ? block.filename : void 0;
18902
18902
  switch (block.type) {
@@ -18957,7 +18957,7 @@ function mapToolResultBlockToAttachment(block) {
18957
18957
  }
18958
18958
  }
18959
18959
  function extractToolResultAttachments(result, counter, attachmentFilter) {
18960
- if (!isRecord$3(result) || result.type !== "content" || !Array.isArray(result.value)) return {
18960
+ if (!isRecord$4(result) || result.type !== "content" || !Array.isArray(result.value)) return {
18961
18961
  resultWithoutAttachments: result,
18962
18962
  attachments: []
18963
18963
  };
@@ -18971,7 +18971,7 @@ function extractToolResultAttachments(result, counter, attachmentFilter) {
18971
18971
  if (shouldIncludeObserverAttachment(attachment, attachmentFilter)) attachments.push(toObserverInputAttachmentPart(attachment));
18972
18972
  const placeholder = formatObserverAttachmentPlaceholder(attachment, counter);
18973
18973
  return {
18974
- type: isRecord$3(block) ? block.type : void 0,
18974
+ type: isRecord$4(block) ? block.type : void 0,
18975
18975
  placeholder
18976
18976
  };
18977
18977
  });
@@ -19592,17 +19592,17 @@ const TRANSIENT_MESSAGE_SUBSTRINGS = [
19592
19592
  "connection reset",
19593
19593
  "connection closed"
19594
19594
  ];
19595
- function isRecord$2(value) {
19595
+ function isRecord$3(value) {
19596
19596
  return typeof value === "object" && value !== null;
19597
19597
  }
19598
19598
  function isAbortError(error) {
19599
- if (!isRecord$2(error)) return false;
19599
+ if (!isRecord$3(error)) return false;
19600
19600
  if (error.name === "AbortError") return true;
19601
19601
  if (typeof error.code === "string" && error.code === "ABORT_ERR") return true;
19602
19602
  return false;
19603
19603
  }
19604
19604
  function hasTransientMessage(value) {
19605
- if (!isRecord$2(value)) return false;
19605
+ if (!isRecord$3(value)) return false;
19606
19606
  const message = typeof value.message === "string" ? value.message.toLowerCase() : "";
19607
19607
  if (message && TRANSIENT_MESSAGE_SUBSTRINGS.some((sub) => message.includes(sub))) return true;
19608
19608
  if (typeof value.code === "string" && value.code.toUpperCase().startsWith("UND_ERR_")) return true;
@@ -19613,13 +19613,13 @@ function isRetryableHttpStatus(status) {
19613
19613
  return status >= 500 && status <= 599;
19614
19614
  }
19615
19615
  function hasRetryableHttpStatus(value) {
19616
- if (!isRecord$2(value)) return false;
19616
+ if (!isRecord$3(value)) return false;
19617
19617
  if (typeof value.statusCode === "number" && isRetryableHttpStatus(value.statusCode)) return true;
19618
19618
  if (typeof value.code === "number" && isRetryableHttpStatus(value.code)) return true;
19619
19619
  return false;
19620
19620
  }
19621
19621
  function hasIsRetryableFlag(value) {
19622
- if (!isRecord$2(value)) return false;
19622
+ if (!isRecord$3(value)) return false;
19623
19623
  return value.isRetryable === true;
19624
19624
  }
19625
19625
  /**
@@ -19637,14 +19637,14 @@ function isTransientLLMError(error) {
19637
19637
  if (isAbortError(error)) return false;
19638
19638
  const visited = /* @__PURE__ */ new WeakSet();
19639
19639
  function visit(candidate) {
19640
- if (isRecord$2(candidate)) {
19640
+ if (isRecord$3(candidate)) {
19641
19641
  if (visited.has(candidate)) return false;
19642
19642
  visited.add(candidate);
19643
19643
  }
19644
19644
  if (hasTransientMessage(candidate)) return true;
19645
19645
  if (hasRetryableHttpStatus(candidate)) return true;
19646
19646
  if (hasIsRetryableFlag(candidate)) return true;
19647
- if (isRecord$2(candidate)) {
19647
+ if (isRecord$3(candidate)) {
19648
19648
  if (visit(candidate.cause)) return true;
19649
19649
  if (visit(candidate.error)) return true;
19650
19650
  }
@@ -19789,6 +19789,37 @@ async function withOmTracingSpan({ phase, model, inputTokens, requestContext, ob
19789
19789
  });
19790
19790
  }
19791
19791
  //#endregion
19792
+ //#region src/processors/observational-memory/transform-hooks.ts
19793
+ /**
19794
+ * Run the `beforeObservation` transform hook. Returns the (possibly replaced)
19795
+ * message array; `undefined` from the hook means passthrough.
19796
+ */
19797
+ async function applyBeforeObservation(hooks, messages, context) {
19798
+ if (!hooks?.beforeObservation) return messages;
19799
+ const result = await hooks.beforeObservation({
19800
+ ...context,
19801
+ messages
19802
+ });
19803
+ if (!result) return messages;
19804
+ omDebug(`[OM:hooks] beforeObservation replaced messages: ${messages.length} -> ${result.messages.length}`);
19805
+ return result.messages;
19806
+ }
19807
+ /**
19808
+ * Run one of the text transform hooks. Returns the (possibly replaced)
19809
+ * observation text; `undefined` from the hook means passthrough.
19810
+ */
19811
+ async function applyTextTransform(hooks, name, observations, context) {
19812
+ const hook = hooks?.[name];
19813
+ if (!hook) return observations;
19814
+ const result = await hook({
19815
+ ...context,
19816
+ observations
19817
+ });
19818
+ if (!result) return observations;
19819
+ omDebug(`[OM:hooks] ${name} replaced observations: ${observations.length} -> ${result.observations.length} chars`);
19820
+ return result.observations;
19821
+ }
19822
+ //#endregion
19792
19823
  //#region src/processors/observational-memory/observer-runner.ts
19793
19824
  function filterObserverExtractors(extractors, skipContinuationHints) {
19794
19825
  const configuredExtractors = extractors ?? [];
@@ -19801,6 +19832,7 @@ var ObserverRunner = class {
19801
19832
  resolveModel;
19802
19833
  tokenCounter;
19803
19834
  memory;
19835
+ hooks;
19804
19836
  mastra;
19805
19837
  /** Captured prompt/response from the last observer call (for repro capture). */
19806
19838
  lastExchange;
@@ -19811,6 +19843,7 @@ var ObserverRunner = class {
19811
19843
  this.tokenCounter = opts.tokenCounter;
19812
19844
  this.mastra = opts.mastra;
19813
19845
  this.memory = opts.memory;
19846
+ this.hooks = opts.hooks;
19814
19847
  }
19815
19848
  __registerMastra(mastra) {
19816
19849
  this.mastra = mastra;
@@ -19864,9 +19897,25 @@ var ObserverRunner = class {
19864
19897
  return result;
19865
19898
  }
19866
19899
  /**
19867
- * Call the Observer agent for a single thread.
19900
+ * Call the Observer agent for a single thread, running the config-level
19901
+ * `beforeObservation` / `afterObservation` transform hooks around it.
19868
19902
  */
19869
19903
  async call(existingObservations, messagesToObserve, abortSignal, options) {
19904
+ const context = {
19905
+ threadId: options?.threadId ?? messagesToObserve[0]?.threadId,
19906
+ resourceId: options?.resourceId,
19907
+ trigger: options?.trigger
19908
+ };
19909
+ const messages = await applyBeforeObservation(this.hooks, messagesToObserve, context);
19910
+ if (messages.length === 0) {
19911
+ omDebug("[OM:callObserver] beforeObservation returned no messages, skipping observer call");
19912
+ return { observations: "" };
19913
+ }
19914
+ const result = await this.callObserver(existingObservations, messages, abortSignal, options);
19915
+ result.observations = await applyTextTransform(this.hooks, "afterObservation", result.observations, context);
19916
+ return result;
19917
+ }
19918
+ async callObserver(existingObservations, messagesToObserve, abortSignal, options) {
19870
19919
  const inputTokens = this.tokenCounter.countMessages(messagesToObserve);
19871
19920
  const resolvedModel = options?.model ? { model: options.model } : this.resolveModel(inputTokens);
19872
19921
  const activeExtractors = await resolveExtractors(filterObserverExtractors(this.observationConfig.extractors, options?.skipContinuationHints), {
@@ -19985,7 +20034,30 @@ var ObserverRunner = class {
19985
20034
  /**
19986
20035
  * Call the Observer agent for multiple threads in a single batched request.
19987
20036
  */
19988
- async callMultiThread(existingObservations, messagesByThread, threadOrder, abortSignal, requestContext, priorMetadataByThread, observabilityContext, model) {
20037
+ async callMultiThread(existingObservations, allMessagesByThread, allThreadOrder, abortSignal, requestContext, priorMetadataByThread, observabilityContext, model, hookContext) {
20038
+ const contextFor = (threadId) => ({
20039
+ threadId,
20040
+ ...hookContext
20041
+ });
20042
+ const messagesByThread = /* @__PURE__ */ new Map();
20043
+ for (const threadId of allThreadOrder) {
20044
+ const filtered = await applyBeforeObservation(this.hooks, allMessagesByThread.get(threadId) ?? [], contextFor(threadId));
20045
+ if (filtered.length > 0) messagesByThread.set(threadId, filtered);
20046
+ }
20047
+ const threadOrder = allThreadOrder.filter((threadId) => messagesByThread.has(threadId));
20048
+ const output = await this.callMultiThreadObserver(existingObservations, messagesByThread, threadOrder, abortSignal, requestContext, priorMetadataByThread, observabilityContext, model);
20049
+ for (const threadId of allThreadOrder) {
20050
+ const threadResult = output.results.get(threadId);
20051
+ if (!threadResult) {
20052
+ output.results.set(threadId, { observations: "" });
20053
+ continue;
20054
+ }
20055
+ threadResult.observations = await applyTextTransform(this.hooks, "afterObservation", threadResult.observations, contextFor(threadId));
20056
+ }
20057
+ return output;
20058
+ }
20059
+ async callMultiThreadObserver(existingObservations, messagesByThread, threadOrder, abortSignal, requestContext, priorMetadataByThread, observabilityContext, model) {
20060
+ if (threadOrder.length === 0) return { results: /* @__PURE__ */ new Map() };
19989
20061
  const inputTokens = Array.from(messagesByThread.values()).reduce((total, messages) => total + this.tokenCounter.countMessages(messages), 0);
19990
20062
  const resolvedModel = model ? { model } : this.resolveModel(inputTokens);
19991
20063
  const firstThreadMessages = messagesByThread.get(threadOrder[0] ?? "") ?? [];
@@ -20004,7 +20076,7 @@ var ObserverRunner = class {
20004
20076
  totalTokens: 0
20005
20077
  };
20006
20078
  for (const threadId of threadOrder) {
20007
- const threadResult = await this.call(existingObservations, messagesByThread.get(threadId) ?? [], abortSignal, {
20079
+ const threadResult = await this.callObserver(existingObservations, messagesByThread.get(threadId) ?? [], abortSignal, {
20008
20080
  requestContext,
20009
20081
  observabilityContext,
20010
20082
  priorCurrentTask: priorMetadataByThread?.get(threadId)?.currentTask,
@@ -23337,6 +23409,45 @@ function didProviderChange(actorModel, lastModel) {
23337
23409
  return false;
23338
23410
  }
23339
23411
  //#endregion
23412
+ //#region src/processors/observational-memory/error.ts
23413
+ function isRecord$2(value) {
23414
+ return typeof value === "object" && value !== null;
23415
+ }
23416
+ /** Keep provider diagnostics in streamed/persisted markers, not whole API request/response objects. */
23417
+ function formatOmError(error) {
23418
+ const details = /* @__PURE__ */ new Set();
23419
+ const visited = /* @__PURE__ */ new Set();
23420
+ const add = (value) => {
23421
+ if (typeof value === "string" && value.trim()) details.add(value.trim().slice(0, 2e3));
23422
+ };
23423
+ function collectErrorDetails(value, depth) {
23424
+ if (depth > 5) return;
23425
+ if (!isRecord$2(value)) {
23426
+ if (value !== void 0) add(String(value));
23427
+ return;
23428
+ }
23429
+ if (visited.has(value)) return;
23430
+ visited.add(value);
23431
+ add(value.message);
23432
+ if (typeof value.statusCode === "number") add(`HTTP ${value.statusCode}`);
23433
+ if (typeof value.responseBody === "string") try {
23434
+ const body = JSON.parse(value.responseBody);
23435
+ if (isRecord$2(body)) {
23436
+ add(body.message);
23437
+ if (isRecord$2(body.error)) add(body.error.message);
23438
+ else add(body.error);
23439
+ }
23440
+ } catch {}
23441
+ if (value.cause !== void 0) collectErrorDetails(value.cause, depth + 1);
23442
+ if (value.error !== void 0) collectErrorDetails(value.error, depth + 1);
23443
+ }
23444
+ try {
23445
+ collectErrorDetails(error, 0);
23446
+ } catch {}
23447
+ const message = [...details].join(": ") || "Unknown error";
23448
+ return message.length > 2e3 ? `${message.slice(0, 1997)}...` : message;
23449
+ }
23450
+ //#endregion
23340
23451
  //#region src/processors/observational-memory/markers.ts
23341
23452
  /**
23342
23453
  * Create a start marker for when observation begins.
@@ -23395,7 +23506,7 @@ function createObservationFailedMarker(params) {
23395
23506
  failedAt,
23396
23507
  durationMs,
23397
23508
  tokensAttempted: params.tokensAttempted,
23398
- error: params.error,
23509
+ error: formatOmError(params.error),
23399
23510
  recordId: params.recordId,
23400
23511
  threadId: params.threadId
23401
23512
  }
@@ -23456,7 +23567,7 @@ function createBufferingFailedMarker(params) {
23456
23567
  failedAt,
23457
23568
  durationMs,
23458
23569
  tokensAttempted: params.tokensAttempted,
23459
- error: params.error,
23570
+ error: formatOmError(params.error),
23460
23571
  recordId: params.recordId,
23461
23572
  threadId: params.threadId
23462
23573
  }
@@ -24061,6 +24172,7 @@ var ObservationStrategy = class ObservationStrategy {
24061
24172
  sendSignal: this.opts.sendSignal,
24062
24173
  sendStateSignal: this.opts.sendStateSignal,
24063
24174
  reflectionHooks,
24175
+ trigger: this.opts.trigger,
24064
24176
  requestContext,
24065
24177
  observabilityContext: this.opts.observabilityContext
24066
24178
  });
@@ -24078,7 +24190,7 @@ var ObservationStrategy = class ObservationStrategy {
24078
24190
  cycleId,
24079
24191
  operationType: "observation",
24080
24192
  startedAt: (/* @__PURE__ */ new Date()).toISOString(),
24081
- error: error instanceof Error ? error.message : String(error),
24193
+ error: formatOmError(error),
24082
24194
  recordId: record.id,
24083
24195
  threadId
24084
24196
  }
@@ -24341,7 +24453,9 @@ var SyncObservationStrategy = class extends ObservationStrategy {
24341
24453
  priorSuggestedResponse: omMeta?.suggestedResponse,
24342
24454
  priorThreadTitle: omMeta?.threadTitle,
24343
24455
  priorExtractedValues: this.priorExtractedValues,
24456
+ threadId: this.opts.threadId,
24344
24457
  resourceId: this.opts.resourceId,
24458
+ trigger: this.opts.trigger,
24345
24459
  mainAgent: this.opts.agent
24346
24460
  });
24347
24461
  const hookedValues = await applyExtractorHooks({
@@ -24477,7 +24591,7 @@ var SyncObservationStrategy = class extends ObservationStrategy {
24477
24591
  operationType: "observation",
24478
24592
  startedAt: this.startedAt,
24479
24593
  tokensAttempted: this.tokensToObserve,
24480
- error: error instanceof Error ? error.message : String(error),
24594
+ error,
24481
24595
  recordId: this.opts.record.id,
24482
24596
  threadId: this.opts.threadId
24483
24597
  });
@@ -24526,7 +24640,9 @@ var AsyncBufferObservationStrategy = class extends ObservationStrategy {
24526
24640
  requestContext: this.opts.requestContext,
24527
24641
  observabilityContext: this.opts.observabilityContext,
24528
24642
  priorExtractedValues: this.priorExtractedValues,
24643
+ threadId: this.opts.threadId,
24529
24644
  resourceId: this.opts.resourceId,
24645
+ trigger: this.opts.trigger,
24530
24646
  mainAgent: this.opts.agent
24531
24647
  });
24532
24648
  const hookedValues = await applyExtractorHooks({
@@ -24676,7 +24792,7 @@ var AsyncBufferObservationStrategy = class extends ObservationStrategy {
24676
24792
  operationType: "observation",
24677
24793
  startedAt: this.startedAt,
24678
24794
  tokensAttempted,
24679
- error: error instanceof Error ? error.message : String(error),
24795
+ error,
24680
24796
  recordId: record.id,
24681
24797
  threadId
24682
24798
  });
@@ -24850,7 +24966,10 @@ var ResourceScopedObservationStrategy = class extends ObservationStrategy {
24850
24966
  }
24851
24967
  if (currentBatch.threadIds.length > 0) batches.push(currentBatch);
24852
24968
  const batchResults = await Promise.all(batches.map(async (batch) => {
24853
- return this.deps.observer.callMultiThread(_existingObservations, batch.threadMap, batch.threadIds, this.opts.abortSignal, this.opts.requestContext, this.priorMetadataByThread, this.opts.observabilityContext);
24969
+ return this.deps.observer.callMultiThread(_existingObservations, batch.threadMap, batch.threadIds, this.opts.abortSignal, this.opts.requestContext, this.priorMetadataByThread, this.opts.observabilityContext, void 0, {
24970
+ resourceId: this.opts.resourceId,
24971
+ trigger: this.opts.trigger
24972
+ });
24854
24973
  }));
24855
24974
  for (const batchResult of batchResults) {
24856
24975
  for (const [threadId, result] of batchResult.results) this.multiThreadResults.set(threadId, result);
@@ -25041,7 +25160,7 @@ var ResourceScopedObservationStrategy = class extends ObservationStrategy {
25041
25160
  operationType: "observation",
25042
25161
  startedAt: this.startedAt,
25043
25162
  tokensAttempted,
25044
- error: error instanceof Error ? error.message : String(error),
25163
+ error,
25045
25164
  recordId: this.opts.record.id,
25046
25165
  threadId
25047
25166
  });
@@ -25188,7 +25307,8 @@ var ObservationStep = class {
25188
25307
  threadId,
25189
25308
  resourceId,
25190
25309
  trigger: "turn-sync"
25191
- })
25310
+ }),
25311
+ trigger: "turn-sync"
25192
25312
  });
25193
25313
  await this.turn.refreshRecord();
25194
25314
  if (this.turn.record.generationCount > preReflectGeneration) reflected = true;
@@ -25391,7 +25511,8 @@ var ObservationStep = class {
25391
25511
  threadId,
25392
25512
  resourceId,
25393
25513
  trigger: "turn-sync"
25394
- })
25514
+ }),
25515
+ trigger: "turn-sync"
25395
25516
  });
25396
25517
  return {
25397
25518
  succeeded: true,
@@ -26028,6 +26149,7 @@ var ReflectorRunner = class {
26028
26149
  getCompressionStartLevel;
26029
26150
  memory;
26030
26151
  onReflectionCommitted;
26152
+ hooks;
26031
26153
  mastra;
26032
26154
  /**
26033
26155
  * Per-lock-key observation-token count of the last unproductive synchronous
@@ -26059,6 +26181,7 @@ var ReflectorRunner = class {
26059
26181
  this.mastra = opts.mastra;
26060
26182
  this.memory = opts.memory;
26061
26183
  this.onReflectionCommitted = opts.onReflectionCommitted;
26184
+ this.hooks = opts.hooks;
26062
26185
  }
26063
26186
  __registerMastra(mastra) {
26064
26187
  this.mastra = mastra;
@@ -26281,7 +26404,7 @@ var ReflectorRunner = class {
26281
26404
  /**
26282
26405
  * Start an async buffered reflection in the background.
26283
26406
  */
26284
- startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal) {
26407
+ startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger) {
26285
26408
  const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
26286
26409
  if (this.buffering.isAsyncBufferingInProgress(bufferKey)) return;
26287
26410
  BufferingCoordinator.lastBufferedBoundary.set(bufferKey, observationTokens);
@@ -26294,7 +26417,7 @@ var ReflectorRunner = class {
26294
26417
  let reflectionError;
26295
26418
  try {
26296
26419
  await reflectionHooks?.onReflectionStart?.();
26297
- outcome = await this.doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal);
26420
+ outcome = await this.doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger);
26298
26421
  } catch (error) {
26299
26422
  reflectionError = error instanceof Error ? error : new Error(String(error));
26300
26423
  if (writer) try {
@@ -26303,7 +26426,7 @@ var ReflectorRunner = class {
26303
26426
  operationType: "reflection",
26304
26427
  startedAt: (/* @__PURE__ */ new Date()).toISOString(),
26305
26428
  tokensAttempted: observationTokens,
26306
- error: reflectionError.message,
26429
+ error,
26307
26430
  recordId: record.id,
26308
26431
  threadId: record.threadId ?? ""
26309
26432
  });
@@ -26340,7 +26463,7 @@ var ReflectorRunner = class {
26340
26463
  * Perform async buffered reflection — reflects observations and stores to bufferedReflection.
26341
26464
  * Does NOT create a new generation or update activeObservations.
26342
26465
  */
26343
- async doAsyncBufferedReflection(record, _bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal) {
26466
+ async doAsyncBufferedReflection(record, _bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger) {
26344
26467
  const currentRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId) ?? record;
26345
26468
  const observationTokens = currentRecord.observationTokenCount ?? 0;
26346
26469
  const reflectThreshold = getMaxThreshold(this.getEffectiveReflectionTokens(currentRecord));
@@ -26353,7 +26476,12 @@ var ReflectorRunner = class {
26353
26476
  const avgTokensPerLine = totalLines > 0 ? observationTokens / totalLines : 0;
26354
26477
  const activationPointTokens = reflectThreshold * bufferActivation;
26355
26478
  const linesToReflect = avgTokensPerLine > 0 ? Math.min(Math.floor(activationPointTokens / avgTokensPerLine), totalLines) : totalLines;
26356
- const activeObservations = allLines.slice(0, linesToReflect).join("\n");
26479
+ const hookContext = {
26480
+ threadId: currentRecord.threadId ?? void 0,
26481
+ resourceId: currentRecord.resourceId ?? void 0,
26482
+ trigger
26483
+ };
26484
+ const activeObservations = await applyTextTransform(this.hooks, "beforeReflection", allLines.slice(0, linesToReflect).join("\n"), hookContext);
26357
26485
  const reflectedObservationLineCount = linesToReflect;
26358
26486
  const sliceTokenEstimate = Math.round(avgTokensPerLine * linesToReflect);
26359
26487
  const compressionTarget = Math.round(sliceTokenEstimate * .75);
@@ -26377,6 +26505,7 @@ var ReflectorRunner = class {
26377
26505
  }
26378
26506
  const compressionStartLevel = await this.getCompressionStartLevel(requestContext);
26379
26507
  const reflectResult = await this.call(activeObservations, void 0, void 0, compressionTarget, void 0, true, compressionStartLevel, requestContext, priorExtractedValues, observabilityContext, void 0, mainAgent, sendSignal);
26508
+ reflectResult.observations = await applyTextTransform(this.hooks, "afterReflection", reflectResult.observations, hookContext);
26380
26509
  await persistThreadExtractedValues(this.storage, this.reflectionConfig.extractors, currentRecord.threadId ?? void 0, reflectResult.extractedValues);
26381
26510
  const reflectionTokenCount = this.tokenCounter.countObservations(reflectResult.observations);
26382
26511
  omDebug(`[OM:reflect] doAsyncBufferedReflection: reflector returned ${reflectionTokenCount} tokens (${reflectResult.observations?.length} chars), saving to recordId=${currentRecord.id}`);
@@ -26523,7 +26652,7 @@ var ReflectorRunner = class {
26523
26652
  * @internal Used by observation strategies. Do not call directly.
26524
26653
  */
26525
26654
  async maybeReflect(opts) {
26526
- const { record, observationTokens, writer, abortSignal, mainAgent, sendSignal, sendStateSignal, messageList, currentModel, reflectionHooks, requestContext, observabilityContext, lastActivityAt, threadId: requestedThreadId } = opts;
26655
+ const { record, observationTokens, writer, abortSignal, mainAgent, sendSignal, sendStateSignal, messageList, currentModel, reflectionHooks, trigger, requestContext, observabilityContext, lastActivityAt, threadId: requestedThreadId } = opts;
26527
26656
  const lockKey = this.buffering.getLockKey(record.threadId, record.resourceId);
26528
26657
  const reflectThreshold = getMaxThreshold(this.getEffectiveReflectionTokens(record));
26529
26658
  const priorExtractedValues = await getThreadExtractedValues(this.storage, this.reflectionConfig.extractors, requestedThreadId ?? record.threadId);
@@ -26541,7 +26670,7 @@ var ReflectorRunner = class {
26541
26670
  if (record.bufferedReflection) return false;
26542
26671
  const activationPoint = reflectThreshold * this.reflectionConfig.bufferActivation;
26543
26672
  return observationTokens >= activationPoint;
26544
- })()) this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal);
26673
+ })()) this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger);
26545
26674
  }
26546
26675
  const activateAfterIdle = resolveActivationTTL(this.reflectionConfig.activateAfterIdle, currentModel);
26547
26676
  const ttlExpiredMs = activateAfterIdle !== void 0 && lastActivityAt !== void 0 ? Date.now() - lastActivityAt : void 0;
@@ -26590,7 +26719,7 @@ var ReflectorRunner = class {
26590
26719
  return;
26591
26720
  }
26592
26721
  omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) — starting background reflection`);
26593
- this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal);
26722
+ this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger);
26594
26723
  return;
26595
26724
  }
26596
26725
  }
@@ -26651,7 +26780,13 @@ var ReflectorRunner = class {
26651
26780
  throw error;
26652
26781
  }
26653
26782
  const compressionStartLevel = await this.getCompressionStartLevel(requestContext);
26654
- const reflectResult = await this.call(record.activeObservations, void 0, streamContext, reflectThreshold, abortSignal, void 0, compressionStartLevel, requestContext, priorExtractedValues, observabilityContext, void 0, mainAgent, sendSignal);
26783
+ const hookContext = {
26784
+ threadId: requestedThreadId ?? record.threadId ?? void 0,
26785
+ resourceId: record.resourceId ?? void 0,
26786
+ trigger
26787
+ };
26788
+ const reflectResult = await this.call(await applyTextTransform(this.hooks, "beforeReflection", record.activeObservations, hookContext), void 0, streamContext, reflectThreshold, abortSignal, void 0, compressionStartLevel, requestContext, priorExtractedValues, observabilityContext, void 0, mainAgent, sendSignal);
26789
+ reflectResult.observations = await applyTextTransform(this.hooks, "afterReflection", reflectResult.observations, hookContext);
26655
26790
  reflectionUsage = reflectResult.usage;
26656
26791
  reflectionProviderMetadata = reflectResult.providerMetadata;
26657
26792
  await persistThreadExtractedValues(this.storage, this.reflectionConfig.extractors, record.threadId ?? void 0, reflectResult.extractedValues);
@@ -26710,7 +26845,7 @@ var ReflectorRunner = class {
26710
26845
  operationType: "reflection",
26711
26846
  startedAt: streamContext.startedAt,
26712
26847
  tokensAttempted: observationTokens,
26713
- error: error instanceof Error ? error.message : String(error),
26848
+ error,
26714
26849
  recordId: record.id,
26715
26850
  threadId
26716
26851
  });
@@ -27402,7 +27537,8 @@ var ObservationalMemory = class ObservationalMemory {
27402
27537
  resolveModel: (inputTokens) => this.resolveObservationModel(inputTokens),
27403
27538
  tokenCounter: this.tokenCounter,
27404
27539
  mastra: config.mastra,
27405
- memory: this.memory
27540
+ memory: this.memory,
27541
+ hooks: this.hooks
27406
27542
  });
27407
27543
  this.buffering = new BufferingCoordinator({
27408
27544
  observationConfig: this.observationConfig,
@@ -27423,7 +27559,8 @@ var ObservationalMemory = class ObservationalMemory {
27423
27559
  resolveModel: (inputTokens) => this.resolveReflectionModel(inputTokens),
27424
27560
  mastra: config.mastra,
27425
27561
  memory: this.memory,
27426
- onReflectionCommitted: config.onReflectionCommitted
27562
+ onReflectionCommitted: config.onReflectionCommitted,
27563
+ hooks: this.hooks
27427
27564
  });
27428
27565
  this.validateBufferConfig();
27429
27566
  omDebug(`[OM:init] new ObservationalMemory instance created — scope=${this.scope}, messageTokens=${JSON.stringify(this.observationConfig.messageTokens)}, obsAsyncEnabled=${this.buffering.isAsyncObservationEnabled()}, bufferTokens=${this.observationConfig.bufferTokens}, bufferActivation=${this.observationConfig.bufferActivation}, blockAfter=${this.observationConfig.blockAfter}, reflectionTokens=${this.reflectionConfig.observationTokens}, refAsyncEnabled=${this.buffering.isAsyncReflectionEnabled()}, refAsyncActivation=${this.reflectionConfig.bufferActivation}, refBlockAfter=${this.reflectionConfig.blockAfter}`);
@@ -28279,7 +28416,8 @@ ${formattedMessages}
28279
28416
  startedAt,
28280
28417
  writer,
28281
28418
  requestContext,
28282
- observabilityContext
28419
+ observabilityContext,
28420
+ trigger: "async-buffer"
28283
28421
  }).run());
28284
28422
  const maxTs = this.getMaxMessageTimestamp(messagesToBuffer);
28285
28423
  const cursor = new Date(maxTs.getTime() + 1);
@@ -28900,7 +29038,8 @@ ${formattedMessages}
28900
29038
  sendStateSignal: opts.sendStateSignal,
28901
29039
  requestContext,
28902
29040
  currentModel: opts.currentModel,
28903
- observabilityContext
29041
+ observabilityContext,
29042
+ trigger: "async-buffer"
28904
29043
  }).run());
28905
29044
  if (isOmReproCaptureEnabled()) writeObserverExchangeReproCapture({
28906
29045
  threadId,
@@ -29214,10 +29353,11 @@ ${formattedMessages}
29214
29353
  async observe(opts) {
29215
29354
  const { threadId, resourceId, messages, requestContext } = opts;
29216
29355
  const lockKey = this.buffering.getLockKey(threadId, resourceId);
29356
+ const trigger = opts.trigger ?? "manual";
29217
29357
  const hooks = this.composeHooks(opts.hooks, {
29218
29358
  threadId,
29219
29359
  resourceId,
29220
- trigger: opts.trigger ?? "manual"
29360
+ trigger
29221
29361
  });
29222
29362
  const reflectionHooks = hooks ? {
29223
29363
  onReflectionStart: hooks.onReflectionStart,
@@ -29248,6 +29388,7 @@ ${formattedMessages}
29248
29388
  messages: unobservedMessages,
29249
29389
  messageList: opts.messageList,
29250
29390
  reflectionHooks,
29391
+ trigger,
29251
29392
  agent: opts.agent,
29252
29393
  sendSignal: opts.sendSignal,
29253
29394
  sendStateSignal: opts.sendStateSignal,
@@ -29314,11 +29455,12 @@ ${formattedMessages}
29314
29455
  }
29315
29456
  await this.storage.setReflectingFlag(record.id, true);
29316
29457
  registerOp(record.id, "reflecting");
29317
- const hooks = this.composeHooks(void 0, {
29458
+ const hookContext = {
29318
29459
  threadId,
29319
29460
  resourceId,
29320
29461
  trigger: "manual"
29321
- });
29462
+ };
29463
+ const hooks = this.composeHooks(void 0, hookContext);
29322
29464
  let reflectionUsage;
29323
29465
  let reflectionProviderMetadata;
29324
29466
  let reflectionError;
@@ -29335,7 +29477,8 @@ ${formattedMessages}
29335
29477
  const previousOmMetadata = getThreadOMMetadata(thread?.metadata);
29336
29478
  const priorExtractedValues = getPriorExtractedValues(previousOmMetadata, this.reflectionConfig.extractors);
29337
29479
  const reflectThreshold = getMaxThreshold(this.getEffectiveReflectionTokens(record));
29338
- const reflectResult = await this.reflector.call(record.activeObservations, prompt, void 0, reflectThreshold, void 0, void 0, void 0, requestContext, priorExtractedValues, observabilityContext, void 0);
29480
+ const reflectResult = await this.reflector.call(await applyTextTransform(this.hooks, "beforeReflection", record.activeObservations, hookContext), prompt, void 0, reflectThreshold, void 0, void 0, void 0, requestContext, priorExtractedValues, observabilityContext, void 0);
29481
+ reflectResult.observations = await applyTextTransform(this.hooks, "afterReflection", reflectResult.observations, hookContext);
29339
29482
  const reflectionTokenCount = this.tokenCounter.countObservations(reflectResult.observations);
29340
29483
  await this.storage.createReflectionGeneration({
29341
29484
  currentRecord: record,
@@ -30233,7 +30376,7 @@ var Memory = class Memory extends MastraMemory {
30233
30376
  });
30234
30377
  }
30235
30378
  async recall(args) {
30236
- const { threadId, resourceId, perPage: perPageArg, page, orderBy, threadConfig, vectorSearchString, includeSystemReminders, filter } = args;
30379
+ const { threadId, resourceId, perPage: perPageArg, page, orderBy, threadConfig, vectorSearchString, includeSystemReminders, filter, includeTotal } = args;
30237
30380
  const config = this.getMergedThreadConfig(threadConfig || {});
30238
30381
  const semanticRecallEnabled = Boolean(config.semanticRecall);
30239
30382
  const span = this.createMemorySpan("recall", args.observabilityContext, {
@@ -30320,6 +30463,7 @@ var Memory = class Memory extends MastraMemory {
30320
30463
  page,
30321
30464
  orderBy: effectiveOrderBy,
30322
30465
  filter,
30466
+ ...includeTotal !== void 0 ? { includeTotal } : {},
30323
30467
  ...filteredVectorResults?.length ? { include: filteredVectorResults.map((r) => ({
30324
30468
  id: r.metadata?.message_id,
30325
30469
  threadId: r.metadata?.thread_id,
@@ -30932,6 +31076,7 @@ ${workingMemory}`;
30932
31076
  direction: "ASC"
30933
31077
  },
30934
31078
  perPage: false,
31079
+ includeTotal: false,
30935
31080
  filter: dateFilter
30936
31081
  })).messages;
30937
31082
  };
@@ -30945,6 +31090,7 @@ ${workingMemory}`;
30945
31090
  direction: "ASC"
30946
31091
  },
30947
31092
  perPage: false,
31093
+ includeTotal: false,
30948
31094
  filter: dateFilter
30949
31095
  })).messages;
30950
31096
  };
@@ -30960,7 +31106,8 @@ ${workingMemory}`;
30960
31106
  field: "createdAt",
30961
31107
  direction: "DESC"
30962
31108
  },
30963
- perPage: typeof lastMessages === "number" ? lastMessages : void 0
31109
+ perPage: typeof lastMessages === "number" ? lastMessages : void 0,
31110
+ includeTotal: false
30964
31111
  })).messages.reverse();
30965
31112
  }
30966
31113
  return {
@@ -31322,7 +31469,8 @@ Notes:
31322
31469
  threadId,
31323
31470
  resourceId,
31324
31471
  perPage: SUMMARIZE_THREAD_DEFAULTS.pageSize,
31325
- page
31472
+ page,
31473
+ includeTotal: false
31326
31474
  });
31327
31475
  if (batch.length === 0) break;
31328
31476
  let reachedLimit = false;
@@ -31973,4 +32121,4 @@ Notes:
31973
32121
  //#endregion
31974
32122
  export { formatMessagesForObserver as A, OBSERVATION_CONTINUATION_HINT as B, SUMMARIZE_THREAD_DEFAULTS as C, buildObserverPrompt as D, OBSERVER_SYSTEM_PROMPT as E, parseAnchorId as F, ModelByInputTokens as G, KnowledgeSemanticIndexCoordinator as H, stripEphemeralAnchorIds as I, publishSubconsciousActivity as J, SUBCONSCIOUS_ACTIVITY_STATE_ID as K, OBSERVATIONAL_MEMORY_DEFAULTS as L, optimizeObservationsForContext as M, parseObserverOutput as N, buildObserverSystemPrompt as O, injectAnchorIds as P, OBSERVATION_CONTEXT_INSTRUCTIONS as R, WorkingMemoryExtractor as S, TokenCounter as T, StaleKnowledgeSemanticIndexError as U, Subconscious as V, SubconsciousRemindExtractor as W, Extractor as X, renderSubconsciousActivity as Y, wrapInObservationGroup as _, extractWorkingMemoryContent as a, WorkingMemoryStateProcessor as b, getObservationsAsOf as c, combineObservationGroupRanges as d, deriveObservationGroupProvenance as f, stripObservationGroups as g, renderObservationGroupsForReflection as h, WorkingMemory as i, hasCurrentTaskSection as j, extractCurrentTask as k, ObservationalMemoryProcessor as l, reconcileObservationGroupsFromReflection as m, MessageHistory$1 as n, extractWorkingMemoryTags as o, parseObservationGroups as p, buildSubconsciousActivitySnapshot as q, SemanticRecall as r, removeWorkingMemoryTags as s, Memory as t, ObservationalMemory as u, WORKING_MEMORY_STATE_ID as v, summarizeConversation as w, deepMergeWorkingMemory as x, WORKING_MEMORY_STATE_PROCESSOR_ID as y, OBSERVATION_CONTEXT_PROMPT as z };
31975
32123
 
31976
- //# sourceMappingURL=src-BFP4tRqs.js.map
32124
+ //# sourceMappingURL=src-BNB8ko_o.js.map