@mastra/server 1.56.0-alpha.2 → 1.56.0-alpha.3

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.
@@ -5961,7 +5961,7 @@ function splitLines(text) {
5961
5961
  return result;
5962
5962
  }
5963
5963
  //#endregion
5964
- //#region ../memory/dist/src-Ci_GvBVm.js
5964
+ //#region ../memory/dist/src-BYZh9IBv.js
5965
5965
  var __defProp$4 = Object.defineProperty;
5966
5966
  var __exportAll = (all, no_symbols) => {
5967
5967
  let target = {};
@@ -26652,7 +26652,10 @@ var ObservationStrategy = class ObservationStrategy {
26652
26652
  await this.persistMarkerToStorage(failedMarkerForStorage, threadId, this.opts.resourceId).catch(() => {});
26653
26653
  if (abortSignal?.aborted) throw error;
26654
26654
  omError("[OM] Observation failed", error);
26655
- return { observed: false };
26655
+ return {
26656
+ observed: false,
26657
+ error: error instanceof Error ? error : new Error(String(error))
26658
+ };
26656
26659
  }
26657
26660
  omError("[OM] Observation failed", error);
26658
26661
  throw error;
@@ -27690,7 +27693,12 @@ var ObservationStep = class {
27690
27693
  currentModel: this.turn.actorModelContext,
27691
27694
  requestContext: this.turn.requestContext,
27692
27695
  observabilityContext: this.turn.observabilityContext,
27693
- lastActivityAt: getLastActivityFromMessages(messageList.get.all.db())
27696
+ lastActivityAt: getLastActivityFromMessages(messageList.get.all.db()),
27697
+ reflectionHooks: om.composeHooks(void 0, {
27698
+ threadId,
27699
+ resourceId,
27700
+ trigger: "turn-sync"
27701
+ })
27694
27702
  });
27695
27703
  await this.turn.refreshRecord();
27696
27704
  if (this.turn.record.generationCount > preReflectGeneration) reflected = true;
@@ -27850,7 +27858,12 @@ var ObservationStep = class {
27850
27858
  currentModel: this.turn.actorModelContext,
27851
27859
  requestContext: this.turn.requestContext,
27852
27860
  observabilityContext: this.turn.observabilityContext,
27853
- lastActivityAt: getLastActivityFromMessages(messageList.get.all.db())
27861
+ lastActivityAt: getLastActivityFromMessages(messageList.get.all.db()),
27862
+ reflectionHooks: om.composeHooks(void 0, {
27863
+ threadId,
27864
+ resourceId,
27865
+ trigger: "turn-sync"
27866
+ })
27854
27867
  });
27855
27868
  return {
27856
27869
  succeeded: true,
@@ -27863,6 +27876,7 @@ var ObservationStep = class {
27863
27876
  threadId,
27864
27877
  resourceId,
27865
27878
  messages: messageList.get.all.db(),
27879
+ trigger: "turn-sync",
27866
27880
  requestContext: this.turn.requestContext,
27867
27881
  writer: this.turn.writer,
27868
27882
  observabilityContext: this.turn.observabilityContext
@@ -28688,12 +28702,16 @@ var ReflectorRunner = class {
28688
28702
  });
28689
28703
  reflectionHooks?.onReflectionStart?.();
28690
28704
  const asyncOp = this.doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal).then((outcome) => {
28691
- reflectionHooks?.onReflectionEnd?.({
28692
- usage: outcome?.usage,
28693
- ...outcome?.providerMetadata ? { providerMetadata: outcome.providerMetadata } : {}
28694
- });
28695
- }).catch(async (error) => {
28696
- if (writer) {
28705
+ try {
28706
+ reflectionHooks?.onReflectionEnd?.({
28707
+ usage: outcome?.usage,
28708
+ ...outcome?.providerMetadata ? { providerMetadata: outcome.providerMetadata } : {}
28709
+ });
28710
+ } catch (hookError) {
28711
+ omError("[OM] onReflectionEnd hook failed after async buffered reflection", hookError);
28712
+ }
28713
+ }, async (error) => {
28714
+ if (writer) try {
28697
28715
  const failedMarker = createBufferingFailedMarker({
28698
28716
  cycleId: `reflect-buf-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
28699
28717
  operationType: "reflection",
@@ -28708,12 +28726,18 @@ var ReflectorRunner = class {
28708
28726
  transient: true
28709
28727
  }).catch(() => {});
28710
28728
  await this.persistMarkerToStorage(failedMarker, record.threadId ?? "", record.resourceId ?? void 0);
28729
+ } catch (markerError) {
28730
+ omError("[OM] Failed to persist buffering-failed marker after async buffered reflection failure", markerError);
28711
28731
  }
28712
28732
  omError("[OM] Async buffered reflection failed", error);
28713
- reflectionHooks?.onReflectionEnd?.({
28714
- usage: void 0,
28715
- error: error instanceof Error ? error : new Error(String(error))
28716
- });
28733
+ try {
28734
+ reflectionHooks?.onReflectionEnd?.({
28735
+ usage: void 0,
28736
+ error: error instanceof Error ? error : new Error(String(error))
28737
+ });
28738
+ } catch (hookError) {
28739
+ omError("[OM] onReflectionEnd hook failed after async buffered reflection failure", hookError);
28740
+ }
28717
28741
  BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
28718
28742
  }).finally(() => {
28719
28743
  BufferingCoordinator.asyncBufferingOps.delete(bufferKey);
@@ -28960,7 +28984,6 @@ var ReflectorRunner = class {
28960
28984
  return;
28961
28985
  }
28962
28986
  }
28963
- reflectionHooks?.onReflectionStart?.();
28964
28987
  await this.storage.setReflectingFlag(record.id, true);
28965
28988
  registerOp(record.id, "reflecting");
28966
28989
  const cycleId = crypto.randomUUID();
@@ -29001,6 +29024,7 @@ var ReflectorRunner = class {
29001
29024
  let reflectionUsage;
29002
29025
  let reflectionProviderMetadata;
29003
29026
  let reflectionError;
29027
+ reflectionHooks?.onReflectionStart?.();
29004
29028
  try {
29005
29029
  const compressionStartLevel = await this.getCompressionStartLevel(requestContext);
29006
29030
  const reflectResult = await this.call(record.activeObservations, void 0, streamContext, reflectThreshold, abortSignal, void 0, compressionStartLevel, requestContext, priorExtractedValues, observabilityContext, void 0, mainAgent, sendSignal);
@@ -29064,12 +29088,15 @@ var ReflectorRunner = class {
29064
29088
  omError("[OM] Reflection failed", error);
29065
29089
  } finally {
29066
29090
  await this.storage.setReflectingFlag(record.id, false);
29067
- reflectionHooks?.onReflectionEnd?.({
29068
- usage: reflectionUsage,
29069
- error: reflectionError,
29070
- ...reflectionProviderMetadata ? { providerMetadata: reflectionProviderMetadata } : {}
29071
- });
29072
- unregisterOp(record.id, "reflecting");
29091
+ try {
29092
+ reflectionHooks?.onReflectionEnd?.({
29093
+ usage: reflectionUsage,
29094
+ error: reflectionError,
29095
+ ...reflectionProviderMetadata ? { providerMetadata: reflectionProviderMetadata } : {}
29096
+ });
29097
+ } finally {
29098
+ unregisterOp(record.id, "reflecting");
29099
+ }
29073
29100
  }
29074
29101
  }
29075
29102
  };
@@ -29518,6 +29545,8 @@ var ObservationalMemory = class ObservationalMemory {
29518
29545
  reflectionConfig;
29519
29546
  onDebugEvent;
29520
29547
  onIndexObservations;
29548
+ /** Config-level lifecycle hooks fired for every observation/reflection cycle. */
29549
+ hooks;
29521
29550
  /** Observer agent runner — handles LLM calls for extracting observations. */
29522
29551
  observer;
29523
29552
  /** Reflector agent runner — handles LLM calls for compressing observations. */
@@ -29578,6 +29607,7 @@ var ObservationalMemory = class ObservationalMemory {
29578
29607
  this.scope = config.scope ?? "thread";
29579
29608
  this.retrieval = Boolean(config.retrieval);
29580
29609
  this.onIndexObservations = config.onIndexObservations;
29610
+ this.hooks = config.hooks;
29581
29611
  this.mastra = config.mastra;
29582
29612
  this.memory = config.memory;
29583
29613
  const resolveModel = (model, defaultModel) => model === "default" ? defaultModel : model;
@@ -30499,7 +30529,11 @@ ${formattedMessages}
30499
30529
  transient: true
30500
30530
  }).catch(() => {});
30501
30531
  omDebug(`[OM:bufferInput] cycleId=${cycleId}, msgCount=${messagesToBuffer.length}, msgTokens=${tokensToBuffer}, ids=${messagesToBuffer.map((m) => `${m.id?.slice(0, 8)}@${m.createdAt ? new Date(m.createdAt).toISOString() : "none"}`).join(",")}`);
30502
- await ObservationStrategy.create(this, {
30532
+ await this.runBufferedObservationCycle({
30533
+ threadId,
30534
+ resourceId: freshRecord.resourceId ?? void 0,
30535
+ trigger: "async-buffer"
30536
+ }, () => ObservationStrategy.create(this, {
30503
30537
  record: freshRecord,
30504
30538
  threadId,
30505
30539
  resourceId: freshRecord.resourceId ?? void 0,
@@ -30509,7 +30543,7 @@ ${formattedMessages}
30509
30543
  writer,
30510
30544
  requestContext,
30511
30545
  observabilityContext
30512
- }).run();
30546
+ }).run());
30513
30547
  const maxTs = this.getMaxMessageTimestamp(messagesToBuffer);
30514
30548
  const cursor = new Date(maxTs.getTime() + 1);
30515
30549
  BufferingCoordinator.lastBufferedAtTime.set(bufferKey, cursor);
@@ -31082,7 +31116,11 @@ ${formattedMessages}
31082
31116
  ...startMarker,
31083
31117
  transient: true
31084
31118
  }).catch(() => {});
31085
- await ObservationStrategy.create(this, {
31119
+ await this.runBufferedObservationCycle({
31120
+ threadId,
31121
+ resourceId: record.resourceId ?? resourceId,
31122
+ trigger: "async-buffer"
31123
+ }, () => ObservationStrategy.create(this, {
31086
31124
  record,
31087
31125
  threadId,
31088
31126
  resourceId: record.resourceId ?? void 0,
@@ -31095,7 +31133,7 @@ ${formattedMessages}
31095
31133
  requestContext,
31096
31134
  currentModel: opts.currentModel,
31097
31135
  observabilityContext
31098
- }).run();
31136
+ }).run());
31099
31137
  if (isOmReproCaptureEnabled()) writeObserverExchangeReproCapture({
31100
31138
  threadId,
31101
31139
  resourceId: record.resourceId ?? void 0,
@@ -31305,6 +31343,88 @@ ${formattedMessages}
31305
31343
  };
31306
31344
  }
31307
31345
  /**
31346
+ * Compose the config-level hooks with optional per-call hooks into a single
31347
+ * `ObserveHooks` object, binding call context onto the config-level
31348
+ * callbacks. Config-level hooks are guarded so a throwing consumer hook can
31349
+ * never fail an observation/reflection cycle; per-call hooks keep their
31350
+ * existing payloads and propagation semantics. Returns undefined when
31351
+ * neither is configured, so call sites stay zero-cost.
31352
+ *
31353
+ * Used internally by every pipeline path (manual observe/reflect,
31354
+ * turn-engine sync observation, async buffering); public only so the
31355
+ * observation turn engine can thread config-level reflection hooks into
31356
+ * reflector calls.
31357
+ *
31358
+ * @internal
31359
+ */
31360
+ composeHooks(callHooks, context) {
31361
+ const configHooks = this.hooks;
31362
+ if (!configHooks) return callHooks;
31363
+ if (!callHooks && !Object.keys(configHooks).length) return void 0;
31364
+ const fireConfigHook = (name, arg) => {
31365
+ const hook = configHooks[name];
31366
+ if (!hook) return;
31367
+ const logHookFailure = (error) => omDebug(`[OM:hooks] config-level ${name} hook failed: ${error instanceof Error ? error.message : String(error)}`);
31368
+ try {
31369
+ const out = hook(arg);
31370
+ if (out && typeof out.then === "function") out.then(void 0, logHookFailure);
31371
+ } catch (error) {
31372
+ logHookFailure(error);
31373
+ }
31374
+ };
31375
+ return {
31376
+ onObservationStart: () => {
31377
+ fireConfigHook("onObservationStart", context);
31378
+ callHooks?.onObservationStart?.();
31379
+ },
31380
+ onObservationEnd: (result) => {
31381
+ fireConfigHook("onObservationEnd", {
31382
+ ...context,
31383
+ ...result
31384
+ });
31385
+ callHooks?.onObservationEnd?.(result);
31386
+ },
31387
+ onReflectionStart: () => {
31388
+ fireConfigHook("onReflectionStart", context);
31389
+ callHooks?.onReflectionStart?.();
31390
+ },
31391
+ onReflectionEnd: (result) => {
31392
+ fireConfigHook("onReflectionEnd", {
31393
+ ...context,
31394
+ ...result
31395
+ });
31396
+ callHooks?.onReflectionEnd?.(result);
31397
+ }
31398
+ };
31399
+ }
31400
+ /**
31401
+ * Run one buffered observation cycle, firing config-level hooks around it.
31402
+ * Shared by both async-buffer lanes — buffer() and
31403
+ * runAsyncBufferedObservation() — whose fire-and-forget callers never see
31404
+ * the strategy result. The async-buffer strategy swallows failures
31405
+ * (rethrowOnFailure=false) and surfaces them on the result instead, so the
31406
+ * end hook reports `error` for failed cycles even though nothing throws.
31407
+ */
31408
+ async runBufferedObservationCycle(context, run) {
31409
+ const hooks = this.composeHooks(void 0, context);
31410
+ hooks?.onObservationStart?.();
31411
+ let runResult;
31412
+ let runError;
31413
+ try {
31414
+ runResult = await run();
31415
+ return runResult;
31416
+ } catch (error) {
31417
+ runError = error instanceof Error ? error : new Error(String(error));
31418
+ throw error;
31419
+ } finally {
31420
+ hooks?.onObservationEnd?.({
31421
+ usage: runResult?.usage,
31422
+ error: runError ?? runResult?.error,
31423
+ ...runResult?.providerMetadata ? { providerMetadata: runResult.providerMetadata } : {}
31424
+ });
31425
+ }
31426
+ }
31427
+ /**
31308
31428
  * Manually trigger observation.
31309
31429
  *
31310
31430
  * When `messages` is provided, those are used directly (filtered for unobserved)
@@ -31315,8 +31435,13 @@ ${formattedMessages}
31315
31435
  * along with the updated record.
31316
31436
  */
31317
31437
  async observe(opts) {
31318
- const { threadId, resourceId, messages, hooks, requestContext } = opts;
31438
+ const { threadId, resourceId, messages, requestContext } = opts;
31319
31439
  const lockKey = this.buffering.getLockKey(threadId, resourceId);
31440
+ const hooks = this.composeHooks(opts.hooks, {
31441
+ threadId,
31442
+ resourceId,
31443
+ trigger: opts.trigger ?? "manual"
31444
+ });
31320
31445
  const reflectionHooks = hooks ? {
31321
31446
  onReflectionStart: hooks.onReflectionStart,
31322
31447
  onReflectionEnd: hooks.onReflectionEnd
@@ -31389,6 +31514,15 @@ ${formattedMessages}
31389
31514
  };
31390
31515
  await this.storage.setReflectingFlag(record.id, true);
31391
31516
  registerOp(record.id, "reflecting");
31517
+ const hooks = this.composeHooks(void 0, {
31518
+ threadId,
31519
+ resourceId,
31520
+ trigger: "manual"
31521
+ });
31522
+ hooks?.onReflectionStart?.();
31523
+ let reflectionUsage;
31524
+ let reflectionProviderMetadata;
31525
+ let reflectionError;
31392
31526
  try {
31393
31527
  const thread = await this.storage.getThreadById({ threadId });
31394
31528
  const previousOmMetadata = (0, _mastra_core_memory.getThreadOMMetadata)(thread?.metadata);
@@ -31418,12 +31552,16 @@ ${formattedMessages}
31418
31552
  metadata: newMetadata
31419
31553
  });
31420
31554
  }
31555
+ const updatedRecord = await this.getOrCreateRecord(threadId, resourceId);
31556
+ reflectionUsage = reflectResult.usage;
31557
+ reflectionProviderMetadata = reflectResult.providerMetadata;
31421
31558
  return {
31422
31559
  reflected: true,
31423
- record: await this.getOrCreateRecord(threadId, resourceId),
31560
+ record: updatedRecord,
31424
31561
  usage: reflectResult.usage
31425
31562
  };
31426
31563
  } catch (error) {
31564
+ reflectionError = error instanceof Error ? error : new Error(String(error));
31427
31565
  omError("[OM] reflect() failed", error);
31428
31566
  return {
31429
31567
  reflected: false,
@@ -31431,6 +31569,11 @@ ${formattedMessages}
31431
31569
  usage: void 0
31432
31570
  };
31433
31571
  } finally {
31572
+ hooks?.onReflectionEnd?.({
31573
+ usage: reflectionUsage,
31574
+ error: reflectionError,
31575
+ ...reflectionProviderMetadata ? { providerMetadata: reflectionProviderMetadata } : {}
31576
+ });
31434
31577
  await this.storage.setReflectingFlag(record.id, false);
31435
31578
  unregisterOp(record.id, "reflecting");
31436
31579
  }
@@ -32997,6 +33140,7 @@ ${workingMemory}`;
32997
33140
  model: omConfig.model,
32998
33141
  mastra: this._mastraInstance,
32999
33142
  onIndexObservations,
33143
+ hooks: omConfig.hooks,
33000
33144
  observation: omConfig.observation ? {
33001
33145
  model: omConfig.observation.model,
33002
33146
  messageTokens: omConfig.observation.messageTokens,
@@ -44288,4 +44432,4 @@ const agentBuilderWorkflows = {
44288
44432
  //#endregion
44289
44433
  exports.agentBuilderWorkflows = agentBuilderWorkflows;
44290
44434
 
44291
- //# sourceMappingURL=dist-3OAfymQm.cjs.map
44435
+ //# sourceMappingURL=dist-CdZrhr1N.cjs.map