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