@mastra/server 1.65.0 → 1.66.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 (30) hide show
  1. package/dist/{datasets-D0C0V2kk.js → datasets-B4qPHzEy.js} +8 -2
  2. package/dist/datasets-B4qPHzEy.js.map +1 -0
  3. package/dist/{datasets-BVbtevHd.cjs → datasets-C-_ZWnxR.cjs} +13 -1
  4. package/dist/datasets-C-_ZWnxR.cjs.map +1 -0
  5. package/dist/{dist-BLvSboHt.js → dist-4Qm6OSPJ.js} +190 -46
  6. package/dist/dist-4Qm6OSPJ.js.map +1 -0
  7. package/dist/{dist-BLP1i9vT.cjs → dist-BmrsK_KX.cjs} +190 -46
  8. package/dist/dist-BmrsK_KX.cjs.map +1 -0
  9. package/dist/docs/SKILL.md +1 -1
  10. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  11. package/dist/docs/references/reference-observability-tracing-trace-query.md +169 -9
  12. package/dist/server/handlers/agent-builder.cjs +1 -1
  13. package/dist/server/handlers/agent-builder.js +1 -1
  14. package/dist/server/handlers/datasets.cjs +5 -4
  15. package/dist/server/handlers/datasets.cjs.map +1 -1
  16. package/dist/server/handlers/datasets.d.ts +2 -0
  17. package/dist/server/handlers/datasets.d.ts.map +1 -1
  18. package/dist/server/handlers/datasets.js +5 -4
  19. package/dist/server/handlers/datasets.js.map +1 -1
  20. package/dist/server/schemas/datasets.d.ts +5 -0
  21. package/dist/server/schemas/datasets.d.ts.map +1 -1
  22. package/dist/server/schemas/index.cjs +2 -1
  23. package/dist/server/schemas/index.js +2 -2
  24. package/dist/server/server-adapter/routes/datasets.d.ts +2 -0
  25. package/dist/server/server-adapter/routes/datasets.d.ts.map +1 -1
  26. package/package.json +6 -6
  27. package/dist/datasets-BVbtevHd.cjs.map +0 -1
  28. package/dist/datasets-D0C0V2kk.js.map +0 -1
  29. package/dist/dist-BLP1i9vT.cjs.map +0 -1
  30. package/dist/dist-BLvSboHt.js.map +0 -1
@@ -4694,7 +4694,7 @@ function splitLines(text) {
4694
4694
  return result;
4695
4695
  }
4696
4696
  //#endregion
4697
- //#region ../memory/dist/src-BFP4tRqs.js
4697
+ //#region ../memory/dist/src-BNB8ko_o.js
4698
4698
  var __defProp$3 = Object.defineProperty;
4699
4699
  var __exportAll = (all, no_symbols) => {
4700
4700
  let target = {};
@@ -23464,11 +23464,11 @@ function formatObserverAttachmentPlaceholder(part, counter) {
23464
23464
  const label = resolveObserverAttachmentLabel(part);
23465
23465
  return label ? `[${attachmentType} #${attachmentId}: ${label}]` : `[${attachmentType} #${attachmentId}]`;
23466
23466
  }
23467
- function isRecord$3(value) {
23467
+ function isRecord$4(value) {
23468
23468
  return !!value && typeof value === "object";
23469
23469
  }
23470
23470
  function mapToolResultBlockToAttachment(block) {
23471
- if (!isRecord$3(block) || typeof block.type !== "string") return;
23471
+ if (!isRecord$4(block) || typeof block.type !== "string") return;
23472
23472
  const mediaType = typeof block.mediaType === "string" ? block.mediaType : void 0;
23473
23473
  const filename = typeof block.filename === "string" ? block.filename : void 0;
23474
23474
  switch (block.type) {
@@ -23529,7 +23529,7 @@ function mapToolResultBlockToAttachment(block) {
23529
23529
  }
23530
23530
  }
23531
23531
  function extractToolResultAttachments(result, counter, attachmentFilter) {
23532
- if (!isRecord$3(result) || result.type !== "content" || !Array.isArray(result.value)) return {
23532
+ if (!isRecord$4(result) || result.type !== "content" || !Array.isArray(result.value)) return {
23533
23533
  resultWithoutAttachments: result,
23534
23534
  attachments: []
23535
23535
  };
@@ -23543,7 +23543,7 @@ function extractToolResultAttachments(result, counter, attachmentFilter) {
23543
23543
  if (shouldIncludeObserverAttachment(attachment, attachmentFilter)) attachments.push(toObserverInputAttachmentPart(attachment));
23544
23544
  const placeholder = formatObserverAttachmentPlaceholder(attachment, counter);
23545
23545
  return {
23546
- type: isRecord$3(block) ? block.type : void 0,
23546
+ type: isRecord$4(block) ? block.type : void 0,
23547
23547
  placeholder
23548
23548
  };
23549
23549
  });
@@ -24162,17 +24162,17 @@ const TRANSIENT_MESSAGE_SUBSTRINGS = [
24162
24162
  "connection reset",
24163
24163
  "connection closed"
24164
24164
  ];
24165
- function isRecord$2(value) {
24165
+ function isRecord$3(value) {
24166
24166
  return typeof value === "object" && value !== null;
24167
24167
  }
24168
24168
  function isAbortError$5(error) {
24169
- if (!isRecord$2(error)) return false;
24169
+ if (!isRecord$3(error)) return false;
24170
24170
  if (error.name === "AbortError") return true;
24171
24171
  if (typeof error.code === "string" && error.code === "ABORT_ERR") return true;
24172
24172
  return false;
24173
24173
  }
24174
24174
  function hasTransientMessage(value) {
24175
- if (!isRecord$2(value)) return false;
24175
+ if (!isRecord$3(value)) return false;
24176
24176
  const message = typeof value.message === "string" ? value.message.toLowerCase() : "";
24177
24177
  if (message && TRANSIENT_MESSAGE_SUBSTRINGS.some((sub) => message.includes(sub))) return true;
24178
24178
  if (typeof value.code === "string" && value.code.toUpperCase().startsWith("UND_ERR_")) return true;
@@ -24183,13 +24183,13 @@ function isRetryableHttpStatus(status) {
24183
24183
  return status >= 500 && status <= 599;
24184
24184
  }
24185
24185
  function hasRetryableHttpStatus(value) {
24186
- if (!isRecord$2(value)) return false;
24186
+ if (!isRecord$3(value)) return false;
24187
24187
  if (typeof value.statusCode === "number" && isRetryableHttpStatus(value.statusCode)) return true;
24188
24188
  if (typeof value.code === "number" && isRetryableHttpStatus(value.code)) return true;
24189
24189
  return false;
24190
24190
  }
24191
24191
  function hasIsRetryableFlag(value) {
24192
- if (!isRecord$2(value)) return false;
24192
+ if (!isRecord$3(value)) return false;
24193
24193
  return value.isRetryable === true;
24194
24194
  }
24195
24195
  /**
@@ -24207,14 +24207,14 @@ function isTransientLLMError(error) {
24207
24207
  if (isAbortError$5(error)) return false;
24208
24208
  const visited = /* @__PURE__ */ new WeakSet();
24209
24209
  function visit(candidate) {
24210
- if (isRecord$2(candidate)) {
24210
+ if (isRecord$3(candidate)) {
24211
24211
  if (visited.has(candidate)) return false;
24212
24212
  visited.add(candidate);
24213
24213
  }
24214
24214
  if (hasTransientMessage(candidate)) return true;
24215
24215
  if (hasRetryableHttpStatus(candidate)) return true;
24216
24216
  if (hasIsRetryableFlag(candidate)) return true;
24217
- if (isRecord$2(candidate)) {
24217
+ if (isRecord$3(candidate)) {
24218
24218
  if (visit(candidate.cause)) return true;
24219
24219
  if (visit(candidate.error)) return true;
24220
24220
  }
@@ -24354,6 +24354,35 @@ async function withOmTracingSpan({ phase, model, inputTokens, requestContext, ob
24354
24354
  }
24355
24355
  });
24356
24356
  }
24357
+ /**
24358
+ * Run the `beforeObservation` transform hook. Returns the (possibly replaced)
24359
+ * message array; `undefined` from the hook means passthrough.
24360
+ */
24361
+ async function applyBeforeObservation(hooks, messages, context) {
24362
+ if (!hooks?.beforeObservation) return messages;
24363
+ const result = await hooks.beforeObservation({
24364
+ ...context,
24365
+ messages
24366
+ });
24367
+ if (!result) return messages;
24368
+ omDebug(`[OM:hooks] beforeObservation replaced messages: ${messages.length} -> ${result.messages.length}`);
24369
+ return result.messages;
24370
+ }
24371
+ /**
24372
+ * Run one of the text transform hooks. Returns the (possibly replaced)
24373
+ * observation text; `undefined` from the hook means passthrough.
24374
+ */
24375
+ async function applyTextTransform(hooks, name, observations, context) {
24376
+ const hook = hooks?.[name];
24377
+ if (!hook) return observations;
24378
+ const result = await hook({
24379
+ ...context,
24380
+ observations
24381
+ });
24382
+ if (!result) return observations;
24383
+ omDebug(`[OM:hooks] ${name} replaced observations: ${observations.length} -> ${result.observations.length} chars`);
24384
+ return result.observations;
24385
+ }
24357
24386
  function filterObserverExtractors(extractors, skipContinuationHints) {
24358
24387
  const configuredExtractors = extractors ?? [];
24359
24388
  if (!skipContinuationHints) return configuredExtractors;
@@ -24365,6 +24394,7 @@ var ObserverRunner = class {
24365
24394
  resolveModel;
24366
24395
  tokenCounter;
24367
24396
  memory;
24397
+ hooks;
24368
24398
  mastra;
24369
24399
  /** Captured prompt/response from the last observer call (for repro capture). */
24370
24400
  lastExchange;
@@ -24375,6 +24405,7 @@ var ObserverRunner = class {
24375
24405
  this.tokenCounter = opts.tokenCounter;
24376
24406
  this.mastra = opts.mastra;
24377
24407
  this.memory = opts.memory;
24408
+ this.hooks = opts.hooks;
24378
24409
  }
24379
24410
  __registerMastra(mastra) {
24380
24411
  this.mastra = mastra;
@@ -24428,9 +24459,25 @@ var ObserverRunner = class {
24428
24459
  return result;
24429
24460
  }
24430
24461
  /**
24431
- * Call the Observer agent for a single thread.
24462
+ * Call the Observer agent for a single thread, running the config-level
24463
+ * `beforeObservation` / `afterObservation` transform hooks around it.
24432
24464
  */
24433
24465
  async call(existingObservations, messagesToObserve, abortSignal, options) {
24466
+ const context = {
24467
+ threadId: options?.threadId ?? messagesToObserve[0]?.threadId,
24468
+ resourceId: options?.resourceId,
24469
+ trigger: options?.trigger
24470
+ };
24471
+ const messages = await applyBeforeObservation(this.hooks, messagesToObserve, context);
24472
+ if (messages.length === 0) {
24473
+ omDebug("[OM:callObserver] beforeObservation returned no messages, skipping observer call");
24474
+ return { observations: "" };
24475
+ }
24476
+ const result = await this.callObserver(existingObservations, messages, abortSignal, options);
24477
+ result.observations = await applyTextTransform(this.hooks, "afterObservation", result.observations, context);
24478
+ return result;
24479
+ }
24480
+ async callObserver(existingObservations, messagesToObserve, abortSignal, options) {
24434
24481
  const inputTokens = this.tokenCounter.countMessages(messagesToObserve);
24435
24482
  const resolvedModel = options?.model ? { model: options.model } : this.resolveModel(inputTokens);
24436
24483
  const activeExtractors = await resolveExtractors(filterObserverExtractors(this.observationConfig.extractors, options?.skipContinuationHints), {
@@ -24549,7 +24596,30 @@ var ObserverRunner = class {
24549
24596
  /**
24550
24597
  * Call the Observer agent for multiple threads in a single batched request.
24551
24598
  */
24552
- async callMultiThread(existingObservations, messagesByThread, threadOrder, abortSignal, requestContext, priorMetadataByThread, observabilityContext, model) {
24599
+ async callMultiThread(existingObservations, allMessagesByThread, allThreadOrder, abortSignal, requestContext, priorMetadataByThread, observabilityContext, model, hookContext) {
24600
+ const contextFor = (threadId) => ({
24601
+ threadId,
24602
+ ...hookContext
24603
+ });
24604
+ const messagesByThread = /* @__PURE__ */ new Map();
24605
+ for (const threadId of allThreadOrder) {
24606
+ const filtered = await applyBeforeObservation(this.hooks, allMessagesByThread.get(threadId) ?? [], contextFor(threadId));
24607
+ if (filtered.length > 0) messagesByThread.set(threadId, filtered);
24608
+ }
24609
+ const threadOrder = allThreadOrder.filter((threadId) => messagesByThread.has(threadId));
24610
+ const output = await this.callMultiThreadObserver(existingObservations, messagesByThread, threadOrder, abortSignal, requestContext, priorMetadataByThread, observabilityContext, model);
24611
+ for (const threadId of allThreadOrder) {
24612
+ const threadResult = output.results.get(threadId);
24613
+ if (!threadResult) {
24614
+ output.results.set(threadId, { observations: "" });
24615
+ continue;
24616
+ }
24617
+ threadResult.observations = await applyTextTransform(this.hooks, "afterObservation", threadResult.observations, contextFor(threadId));
24618
+ }
24619
+ return output;
24620
+ }
24621
+ async callMultiThreadObserver(existingObservations, messagesByThread, threadOrder, abortSignal, requestContext, priorMetadataByThread, observabilityContext, model) {
24622
+ if (threadOrder.length === 0) return { results: /* @__PURE__ */ new Map() };
24553
24623
  const inputTokens = Array.from(messagesByThread.values()).reduce((total, messages) => total + this.tokenCounter.countMessages(messages), 0);
24554
24624
  const resolvedModel = model ? { model } : this.resolveModel(inputTokens);
24555
24625
  const firstThreadMessages = messagesByThread.get(threadOrder[0] ?? "") ?? [];
@@ -24568,7 +24638,7 @@ var ObserverRunner = class {
24568
24638
  totalTokens: 0
24569
24639
  };
24570
24640
  for (const threadId of threadOrder) {
24571
- const threadResult = await this.call(existingObservations, messagesByThread.get(threadId) ?? [], abortSignal, {
24641
+ const threadResult = await this.callObserver(existingObservations, messagesByThread.get(threadId) ?? [], abortSignal, {
24572
24642
  requestContext,
24573
24643
  observabilityContext,
24574
24644
  priorCurrentTask: priorMetadataByThread?.get(threadId)?.currentTask,
@@ -27876,6 +27946,43 @@ function didProviderChange(actorModel, lastModel) {
27876
27946
  if (actorContext.provider && lastContext.provider) return actorContext.provider !== lastContext.provider;
27877
27947
  return false;
27878
27948
  }
27949
+ function isRecord$2(value) {
27950
+ return typeof value === "object" && value !== null;
27951
+ }
27952
+ /** Keep provider diagnostics in streamed/persisted markers, not whole API request/response objects. */
27953
+ function formatOmError(error) {
27954
+ const details = /* @__PURE__ */ new Set();
27955
+ const visited = /* @__PURE__ */ new Set();
27956
+ const add = (value) => {
27957
+ if (typeof value === "string" && value.trim()) details.add(value.trim().slice(0, 2e3));
27958
+ };
27959
+ function collectErrorDetails(value, depth) {
27960
+ if (depth > 5) return;
27961
+ if (!isRecord$2(value)) {
27962
+ if (value !== void 0) add(String(value));
27963
+ return;
27964
+ }
27965
+ if (visited.has(value)) return;
27966
+ visited.add(value);
27967
+ add(value.message);
27968
+ if (typeof value.statusCode === "number") add(`HTTP ${value.statusCode}`);
27969
+ if (typeof value.responseBody === "string") try {
27970
+ const body = JSON.parse(value.responseBody);
27971
+ if (isRecord$2(body)) {
27972
+ add(body.message);
27973
+ if (isRecord$2(body.error)) add(body.error.message);
27974
+ else add(body.error);
27975
+ }
27976
+ } catch {}
27977
+ if (value.cause !== void 0) collectErrorDetails(value.cause, depth + 1);
27978
+ if (value.error !== void 0) collectErrorDetails(value.error, depth + 1);
27979
+ }
27980
+ try {
27981
+ collectErrorDetails(error, 0);
27982
+ } catch {}
27983
+ const message = [...details].join(": ") || "Unknown error";
27984
+ return message.length > 2e3 ? `${message.slice(0, 1997)}...` : message;
27985
+ }
27879
27986
  /**
27880
27987
  * Create a start marker for when observation begins.
27881
27988
  */
@@ -27933,7 +28040,7 @@ function createObservationFailedMarker(params) {
27933
28040
  failedAt,
27934
28041
  durationMs,
27935
28042
  tokensAttempted: params.tokensAttempted,
27936
- error: params.error,
28043
+ error: formatOmError(params.error),
27937
28044
  recordId: params.recordId,
27938
28045
  threadId: params.threadId
27939
28046
  }
@@ -27994,7 +28101,7 @@ function createBufferingFailedMarker(params) {
27994
28101
  failedAt,
27995
28102
  durationMs,
27996
28103
  tokensAttempted: params.tokensAttempted,
27997
- error: params.error,
28104
+ error: formatOmError(params.error),
27998
28105
  recordId: params.recordId,
27999
28106
  threadId: params.threadId
28000
28107
  }
@@ -28591,6 +28698,7 @@ var ObservationStrategy = class ObservationStrategy {
28591
28698
  sendSignal: this.opts.sendSignal,
28592
28699
  sendStateSignal: this.opts.sendStateSignal,
28593
28700
  reflectionHooks,
28701
+ trigger: this.opts.trigger,
28594
28702
  requestContext,
28595
28703
  observabilityContext: this.opts.observabilityContext
28596
28704
  });
@@ -28608,7 +28716,7 @@ var ObservationStrategy = class ObservationStrategy {
28608
28716
  cycleId,
28609
28717
  operationType: "observation",
28610
28718
  startedAt: (/* @__PURE__ */ new Date()).toISOString(),
28611
- error: error instanceof Error ? error.message : String(error),
28719
+ error: formatOmError(error),
28612
28720
  recordId: record.id,
28613
28721
  threadId
28614
28722
  }
@@ -28869,7 +28977,9 @@ var SyncObservationStrategy = class extends ObservationStrategy {
28869
28977
  priorSuggestedResponse: omMeta?.suggestedResponse,
28870
28978
  priorThreadTitle: omMeta?.threadTitle,
28871
28979
  priorExtractedValues: this.priorExtractedValues,
28980
+ threadId: this.opts.threadId,
28872
28981
  resourceId: this.opts.resourceId,
28982
+ trigger: this.opts.trigger,
28873
28983
  mainAgent: this.opts.agent
28874
28984
  });
28875
28985
  const hookedValues = await applyExtractorHooks({
@@ -29005,7 +29115,7 @@ var SyncObservationStrategy = class extends ObservationStrategy {
29005
29115
  operationType: "observation",
29006
29116
  startedAt: this.startedAt,
29007
29117
  tokensAttempted: this.tokensToObserve,
29008
- error: error instanceof Error ? error.message : String(error),
29118
+ error,
29009
29119
  recordId: this.opts.record.id,
29010
29120
  threadId: this.opts.threadId
29011
29121
  });
@@ -29052,7 +29162,9 @@ var AsyncBufferObservationStrategy = class extends ObservationStrategy {
29052
29162
  requestContext: this.opts.requestContext,
29053
29163
  observabilityContext: this.opts.observabilityContext,
29054
29164
  priorExtractedValues: this.priorExtractedValues,
29165
+ threadId: this.opts.threadId,
29055
29166
  resourceId: this.opts.resourceId,
29167
+ trigger: this.opts.trigger,
29056
29168
  mainAgent: this.opts.agent
29057
29169
  });
29058
29170
  const hookedValues = await applyExtractorHooks({
@@ -29202,7 +29314,7 @@ var AsyncBufferObservationStrategy = class extends ObservationStrategy {
29202
29314
  operationType: "observation",
29203
29315
  startedAt: this.startedAt,
29204
29316
  tokensAttempted,
29205
- error: error instanceof Error ? error.message : String(error),
29317
+ error,
29206
29318
  recordId: record.id,
29207
29319
  threadId
29208
29320
  });
@@ -29374,7 +29486,10 @@ var ResourceScopedObservationStrategy = class extends ObservationStrategy {
29374
29486
  }
29375
29487
  if (currentBatch.threadIds.length > 0) batches.push(currentBatch);
29376
29488
  const batchResults = await Promise.all(batches.map(async (batch) => {
29377
- return this.deps.observer.callMultiThread(_existingObservations, batch.threadMap, batch.threadIds, this.opts.abortSignal, this.opts.requestContext, this.priorMetadataByThread, this.opts.observabilityContext);
29489
+ return this.deps.observer.callMultiThread(_existingObservations, batch.threadMap, batch.threadIds, this.opts.abortSignal, this.opts.requestContext, this.priorMetadataByThread, this.opts.observabilityContext, void 0, {
29490
+ resourceId: this.opts.resourceId,
29491
+ trigger: this.opts.trigger
29492
+ });
29378
29493
  }));
29379
29494
  for (const batchResult of batchResults) {
29380
29495
  for (const [threadId, result] of batchResult.results) this.multiThreadResults.set(threadId, result);
@@ -29565,7 +29680,7 @@ var ResourceScopedObservationStrategy = class extends ObservationStrategy {
29565
29680
  operationType: "observation",
29566
29681
  startedAt: this.startedAt,
29567
29682
  tokensAttempted,
29568
- error: error instanceof Error ? error.message : String(error),
29683
+ error,
29569
29684
  recordId: this.opts.record.id,
29570
29685
  threadId
29571
29686
  });
@@ -29706,7 +29821,8 @@ var ObservationStep = class {
29706
29821
  threadId,
29707
29822
  resourceId,
29708
29823
  trigger: "turn-sync"
29709
- })
29824
+ }),
29825
+ trigger: "turn-sync"
29710
29826
  });
29711
29827
  await this.turn.refreshRecord();
29712
29828
  if (this.turn.record.generationCount > preReflectGeneration) reflected = true;
@@ -29909,7 +30025,8 @@ var ObservationStep = class {
29909
30025
  threadId,
29910
30026
  resourceId,
29911
30027
  trigger: "turn-sync"
29912
- })
30028
+ }),
30029
+ trigger: "turn-sync"
29913
30030
  });
29914
30031
  return {
29915
30032
  succeeded: true,
@@ -30540,6 +30657,7 @@ var ReflectorRunner = class {
30540
30657
  getCompressionStartLevel;
30541
30658
  memory;
30542
30659
  onReflectionCommitted;
30660
+ hooks;
30543
30661
  mastra;
30544
30662
  /**
30545
30663
  * Per-lock-key observation-token count of the last unproductive synchronous
@@ -30571,6 +30689,7 @@ var ReflectorRunner = class {
30571
30689
  this.mastra = opts.mastra;
30572
30690
  this.memory = opts.memory;
30573
30691
  this.onReflectionCommitted = opts.onReflectionCommitted;
30692
+ this.hooks = opts.hooks;
30574
30693
  }
30575
30694
  __registerMastra(mastra) {
30576
30695
  this.mastra = mastra;
@@ -30793,7 +30912,7 @@ var ReflectorRunner = class {
30793
30912
  /**
30794
30913
  * Start an async buffered reflection in the background.
30795
30914
  */
30796
- startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal) {
30915
+ startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger) {
30797
30916
  const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
30798
30917
  if (this.buffering.isAsyncBufferingInProgress(bufferKey)) return;
30799
30918
  BufferingCoordinator.lastBufferedBoundary.set(bufferKey, observationTokens);
@@ -30806,7 +30925,7 @@ var ReflectorRunner = class {
30806
30925
  let reflectionError;
30807
30926
  try {
30808
30927
  await reflectionHooks?.onReflectionStart?.();
30809
- outcome = await this.doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal);
30928
+ outcome = await this.doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger);
30810
30929
  } catch (error) {
30811
30930
  reflectionError = error instanceof Error ? error : new Error(String(error));
30812
30931
  if (writer) try {
@@ -30815,7 +30934,7 @@ var ReflectorRunner = class {
30815
30934
  operationType: "reflection",
30816
30935
  startedAt: (/* @__PURE__ */ new Date()).toISOString(),
30817
30936
  tokensAttempted: observationTokens,
30818
- error: reflectionError.message,
30937
+ error,
30819
30938
  recordId: record.id,
30820
30939
  threadId: record.threadId ?? ""
30821
30940
  });
@@ -30852,7 +30971,7 @@ var ReflectorRunner = class {
30852
30971
  * Perform async buffered reflection — reflects observations and stores to bufferedReflection.
30853
30972
  * Does NOT create a new generation or update activeObservations.
30854
30973
  */
30855
- async doAsyncBufferedReflection(record, _bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal) {
30974
+ async doAsyncBufferedReflection(record, _bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger) {
30856
30975
  const currentRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId) ?? record;
30857
30976
  const observationTokens = currentRecord.observationTokenCount ?? 0;
30858
30977
  const reflectThreshold = getMaxThreshold(this.getEffectiveReflectionTokens(currentRecord));
@@ -30865,7 +30984,12 @@ var ReflectorRunner = class {
30865
30984
  const avgTokensPerLine = totalLines > 0 ? observationTokens / totalLines : 0;
30866
30985
  const activationPointTokens = reflectThreshold * bufferActivation;
30867
30986
  const linesToReflect = avgTokensPerLine > 0 ? Math.min(Math.floor(activationPointTokens / avgTokensPerLine), totalLines) : totalLines;
30868
- const activeObservations = allLines.slice(0, linesToReflect).join("\n");
30987
+ const hookContext = {
30988
+ threadId: currentRecord.threadId ?? void 0,
30989
+ resourceId: currentRecord.resourceId ?? void 0,
30990
+ trigger
30991
+ };
30992
+ const activeObservations = await applyTextTransform(this.hooks, "beforeReflection", allLines.slice(0, linesToReflect).join("\n"), hookContext);
30869
30993
  const reflectedObservationLineCount = linesToReflect;
30870
30994
  const sliceTokenEstimate = Math.round(avgTokensPerLine * linesToReflect);
30871
30995
  const compressionTarget = Math.round(sliceTokenEstimate * .75);
@@ -30889,6 +31013,7 @@ var ReflectorRunner = class {
30889
31013
  }
30890
31014
  const compressionStartLevel = await this.getCompressionStartLevel(requestContext);
30891
31015
  const reflectResult = await this.call(activeObservations, void 0, void 0, compressionTarget, void 0, true, compressionStartLevel, requestContext, priorExtractedValues, observabilityContext, void 0, mainAgent, sendSignal);
31016
+ reflectResult.observations = await applyTextTransform(this.hooks, "afterReflection", reflectResult.observations, hookContext);
30892
31017
  await persistThreadExtractedValues(this.storage, this.reflectionConfig.extractors, currentRecord.threadId ?? void 0, reflectResult.extractedValues);
30893
31018
  const reflectionTokenCount = this.tokenCounter.countObservations(reflectResult.observations);
30894
31019
  omDebug(`[OM:reflect] doAsyncBufferedReflection: reflector returned ${reflectionTokenCount} tokens (${reflectResult.observations?.length} chars), saving to recordId=${currentRecord.id}`);
@@ -31035,7 +31160,7 @@ var ReflectorRunner = class {
31035
31160
  * @internal Used by observation strategies. Do not call directly.
31036
31161
  */
31037
31162
  async maybeReflect(opts) {
31038
- const { record, observationTokens, writer, abortSignal, mainAgent, sendSignal, sendStateSignal, messageList, currentModel, reflectionHooks, requestContext, observabilityContext, lastActivityAt, threadId: requestedThreadId } = opts;
31163
+ const { record, observationTokens, writer, abortSignal, mainAgent, sendSignal, sendStateSignal, messageList, currentModel, reflectionHooks, trigger, requestContext, observabilityContext, lastActivityAt, threadId: requestedThreadId } = opts;
31039
31164
  const lockKey = this.buffering.getLockKey(record.threadId, record.resourceId);
31040
31165
  const reflectThreshold = getMaxThreshold(this.getEffectiveReflectionTokens(record));
31041
31166
  const priorExtractedValues = await getThreadExtractedValues(this.storage, this.reflectionConfig.extractors, requestedThreadId ?? record.threadId);
@@ -31053,7 +31178,7 @@ var ReflectorRunner = class {
31053
31178
  if (record.bufferedReflection) return false;
31054
31179
  const activationPoint = reflectThreshold * this.reflectionConfig.bufferActivation;
31055
31180
  return observationTokens >= activationPoint;
31056
- })()) this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal);
31181
+ })()) this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger);
31057
31182
  }
31058
31183
  const activateAfterIdle = resolveActivationTTL(this.reflectionConfig.activateAfterIdle, currentModel);
31059
31184
  const ttlExpiredMs = activateAfterIdle !== void 0 && lastActivityAt !== void 0 ? Date.now() - lastActivityAt : void 0;
@@ -31102,7 +31227,7 @@ var ReflectorRunner = class {
31102
31227
  return;
31103
31228
  }
31104
31229
  omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) — starting background reflection`);
31105
- this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal);
31230
+ this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger);
31106
31231
  return;
31107
31232
  }
31108
31233
  }
@@ -31163,7 +31288,13 @@ var ReflectorRunner = class {
31163
31288
  throw error;
31164
31289
  }
31165
31290
  const compressionStartLevel = await this.getCompressionStartLevel(requestContext);
31166
- const reflectResult = await this.call(record.activeObservations, void 0, streamContext, reflectThreshold, abortSignal, void 0, compressionStartLevel, requestContext, priorExtractedValues, observabilityContext, void 0, mainAgent, sendSignal);
31291
+ const hookContext = {
31292
+ threadId: requestedThreadId ?? record.threadId ?? void 0,
31293
+ resourceId: record.resourceId ?? void 0,
31294
+ trigger
31295
+ };
31296
+ 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);
31297
+ reflectResult.observations = await applyTextTransform(this.hooks, "afterReflection", reflectResult.observations, hookContext);
31167
31298
  reflectionUsage = reflectResult.usage;
31168
31299
  reflectionProviderMetadata = reflectResult.providerMetadata;
31169
31300
  await persistThreadExtractedValues(this.storage, this.reflectionConfig.extractors, record.threadId ?? void 0, reflectResult.extractedValues);
@@ -31222,7 +31353,7 @@ var ReflectorRunner = class {
31222
31353
  operationType: "reflection",
31223
31354
  startedAt: streamContext.startedAt,
31224
31355
  tokensAttempted: observationTokens,
31225
- error: error instanceof Error ? error.message : String(error),
31356
+ error,
31226
31357
  recordId: record.id,
31227
31358
  threadId
31228
31359
  });
@@ -31910,7 +32041,8 @@ var ObservationalMemory = class ObservationalMemory {
31910
32041
  resolveModel: (inputTokens) => this.resolveObservationModel(inputTokens),
31911
32042
  tokenCounter: this.tokenCounter,
31912
32043
  mastra: config.mastra,
31913
- memory: this.memory
32044
+ memory: this.memory,
32045
+ hooks: this.hooks
31914
32046
  });
31915
32047
  this.buffering = new BufferingCoordinator({
31916
32048
  observationConfig: this.observationConfig,
@@ -31931,7 +32063,8 @@ var ObservationalMemory = class ObservationalMemory {
31931
32063
  resolveModel: (inputTokens) => this.resolveReflectionModel(inputTokens),
31932
32064
  mastra: config.mastra,
31933
32065
  memory: this.memory,
31934
- onReflectionCommitted: config.onReflectionCommitted
32066
+ onReflectionCommitted: config.onReflectionCommitted,
32067
+ hooks: this.hooks
31935
32068
  });
31936
32069
  this.validateBufferConfig();
31937
32070
  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}`);
@@ -32787,7 +32920,8 @@ ${formattedMessages}
32787
32920
  startedAt,
32788
32921
  writer,
32789
32922
  requestContext,
32790
- observabilityContext
32923
+ observabilityContext,
32924
+ trigger: "async-buffer"
32791
32925
  }).run());
32792
32926
  const maxTs = this.getMaxMessageTimestamp(messagesToBuffer);
32793
32927
  const cursor = new Date(maxTs.getTime() + 1);
@@ -33408,7 +33542,8 @@ ${formattedMessages}
33408
33542
  sendStateSignal: opts.sendStateSignal,
33409
33543
  requestContext,
33410
33544
  currentModel: opts.currentModel,
33411
- observabilityContext
33545
+ observabilityContext,
33546
+ trigger: "async-buffer"
33412
33547
  }).run());
33413
33548
  if (isOmReproCaptureEnabled()) writeObserverExchangeReproCapture({
33414
33549
  threadId,
@@ -33722,10 +33857,11 @@ ${formattedMessages}
33722
33857
  async observe(opts) {
33723
33858
  const { threadId, resourceId, messages, requestContext } = opts;
33724
33859
  const lockKey = this.buffering.getLockKey(threadId, resourceId);
33860
+ const trigger = opts.trigger ?? "manual";
33725
33861
  const hooks = this.composeHooks(opts.hooks, {
33726
33862
  threadId,
33727
33863
  resourceId,
33728
- trigger: opts.trigger ?? "manual"
33864
+ trigger
33729
33865
  });
33730
33866
  const reflectionHooks = hooks ? {
33731
33867
  onReflectionStart: hooks.onReflectionStart,
@@ -33756,6 +33892,7 @@ ${formattedMessages}
33756
33892
  messages: unobservedMessages,
33757
33893
  messageList: opts.messageList,
33758
33894
  reflectionHooks,
33895
+ trigger,
33759
33896
  agent: opts.agent,
33760
33897
  sendSignal: opts.sendSignal,
33761
33898
  sendStateSignal: opts.sendStateSignal,
@@ -33822,11 +33959,12 @@ ${formattedMessages}
33822
33959
  }
33823
33960
  await this.storage.setReflectingFlag(record.id, true);
33824
33961
  registerOp(record.id, "reflecting");
33825
- const hooks = this.composeHooks(void 0, {
33962
+ const hookContext = {
33826
33963
  threadId,
33827
33964
  resourceId,
33828
33965
  trigger: "manual"
33829
- });
33966
+ };
33967
+ const hooks = this.composeHooks(void 0, hookContext);
33830
33968
  let reflectionUsage;
33831
33969
  let reflectionProviderMetadata;
33832
33970
  let reflectionError;
@@ -33843,7 +33981,8 @@ ${formattedMessages}
33843
33981
  const previousOmMetadata = (0, _mastra_core_memory.getThreadOMMetadata)(thread?.metadata);
33844
33982
  const priorExtractedValues = getPriorExtractedValues(previousOmMetadata, this.reflectionConfig.extractors);
33845
33983
  const reflectThreshold = getMaxThreshold(this.getEffectiveReflectionTokens(record));
33846
- const reflectResult = await this.reflector.call(record.activeObservations, prompt, void 0, reflectThreshold, void 0, void 0, void 0, requestContext, priorExtractedValues, observabilityContext, void 0);
33984
+ 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);
33985
+ reflectResult.observations = await applyTextTransform(this.hooks, "afterReflection", reflectResult.observations, hookContext);
33847
33986
  const reflectionTokenCount = this.tokenCounter.countObservations(reflectResult.observations);
33848
33987
  await this.storage.createReflectionGeneration({
33849
33988
  currentRecord: record,
@@ -34716,7 +34855,7 @@ var Memory = class Memory extends _mastra_core_memory.MastraMemory {
34716
34855
  });
34717
34856
  }
34718
34857
  async recall(args) {
34719
- const { threadId, resourceId, perPage: perPageArg, page, orderBy, threadConfig, vectorSearchString, includeSystemReminders, filter } = args;
34858
+ const { threadId, resourceId, perPage: perPageArg, page, orderBy, threadConfig, vectorSearchString, includeSystemReminders, filter, includeTotal } = args;
34720
34859
  const config = this.getMergedThreadConfig(threadConfig || {});
34721
34860
  const semanticRecallEnabled = Boolean(config.semanticRecall);
34722
34861
  const span = this.createMemorySpan("recall", args.observabilityContext, {
@@ -34803,6 +34942,7 @@ var Memory = class Memory extends _mastra_core_memory.MastraMemory {
34803
34942
  page,
34804
34943
  orderBy: effectiveOrderBy,
34805
34944
  filter,
34945
+ ...includeTotal !== void 0 ? { includeTotal } : {},
34806
34946
  ...filteredVectorResults?.length ? { include: filteredVectorResults.map((r) => ({
34807
34947
  id: r.metadata?.message_id,
34808
34948
  threadId: r.metadata?.thread_id,
@@ -35415,6 +35555,7 @@ ${workingMemory}`;
35415
35555
  direction: "ASC"
35416
35556
  },
35417
35557
  perPage: false,
35558
+ includeTotal: false,
35418
35559
  filter: dateFilter
35419
35560
  })).messages;
35420
35561
  };
@@ -35428,6 +35569,7 @@ ${workingMemory}`;
35428
35569
  direction: "ASC"
35429
35570
  },
35430
35571
  perPage: false,
35572
+ includeTotal: false,
35431
35573
  filter: dateFilter
35432
35574
  })).messages;
35433
35575
  };
@@ -35443,7 +35585,8 @@ ${workingMemory}`;
35443
35585
  field: "createdAt",
35444
35586
  direction: "DESC"
35445
35587
  },
35446
- perPage: typeof lastMessages === "number" ? lastMessages : void 0
35588
+ perPage: typeof lastMessages === "number" ? lastMessages : void 0,
35589
+ includeTotal: false
35447
35590
  })).messages.reverse();
35448
35591
  }
35449
35592
  return {
@@ -35805,7 +35948,8 @@ Notes:
35805
35948
  threadId,
35806
35949
  resourceId,
35807
35950
  perPage: SUMMARIZE_THREAD_DEFAULTS.pageSize,
35808
- page
35951
+ page,
35952
+ includeTotal: false
35809
35953
  });
35810
35954
  if (batch.length === 0) break;
35811
35955
  let reachedLimit = false;
@@ -46839,4 +46983,4 @@ const agentBuilderWorkflows = {
46839
46983
  //#endregion
46840
46984
  exports.agentBuilderWorkflows = agentBuilderWorkflows;
46841
46985
 
46842
- //# sourceMappingURL=dist-BLP1i9vT.cjs.map
46986
+ //# sourceMappingURL=dist-BmrsK_KX.cjs.map