@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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # @mastra/server
2
2
 
3
+ ## 1.56.0-alpha.3
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [[`594f7b2`](https://github.com/mastra-ai/mastra/commit/594f7b28f5263fb9982fd50d95c471fb971ea984), [`311f943`](https://github.com/mastra-ai/mastra/commit/311f943bee60e8fdf5c84499ea50e884276c936c), [`0c89896`](https://github.com/mastra-ai/mastra/commit/0c8989673fb7d106837098398131e570c6023b68), [`23b4238`](https://github.com/mastra-ai/mastra/commit/23b423844ad0bcf2a502a68dd62866d6160f9f6d), [`e320a76`](https://github.com/mastra-ai/mastra/commit/e320a763feaf65c6be3cebecf746defcbde161b3), [`03b4918`](https://github.com/mastra-ai/mastra/commit/03b4918c80d188ce375334c393e131c6e94bd7eb), [`14ef73a`](https://github.com/mastra-ai/mastra/commit/14ef73a4bbd73e7808414816eb0628ce1d80b5d7), [`1d677d5`](https://github.com/mastra-ai/mastra/commit/1d677d5f99d7db403f7828585e8c25f299f72628), [`93e28ec`](https://github.com/mastra-ai/mastra/commit/93e28ecce9031c02397e0ae8406593e5c7a95883), [`729dab4`](https://github.com/mastra-ai/mastra/commit/729dab408faccfaef0cbb048e5a4338f9172847e), [`484003d`](https://github.com/mastra-ai/mastra/commit/484003d33ff59330c86b19863e4a38732d7e4155), [`933d291`](https://github.com/mastra-ai/mastra/commit/933d291146b789c19442ad206f94da3e4be90c64)]:
8
+ - @mastra/core@1.56.0-alpha.3
9
+
3
10
  ## 1.56.0-alpha.2
4
11
 
5
12
  ### Patch Changes
@@ -5958,7 +5958,7 @@ function splitLines(text) {
5958
5958
  return result;
5959
5959
  }
5960
5960
  //#endregion
5961
- //#region ../memory/dist/src-Ci_GvBVm.js
5961
+ //#region ../memory/dist/src-BYZh9IBv.js
5962
5962
  var __defProp$4 = Object.defineProperty;
5963
5963
  var __exportAll = (all, no_symbols) => {
5964
5964
  let target = {};
@@ -26649,7 +26649,10 @@ var ObservationStrategy = class ObservationStrategy {
26649
26649
  await this.persistMarkerToStorage(failedMarkerForStorage, threadId, this.opts.resourceId).catch(() => {});
26650
26650
  if (abortSignal?.aborted) throw error;
26651
26651
  omError("[OM] Observation failed", error);
26652
- return { observed: false };
26652
+ return {
26653
+ observed: false,
26654
+ error: error instanceof Error ? error : new Error(String(error))
26655
+ };
26653
26656
  }
26654
26657
  omError("[OM] Observation failed", error);
26655
26658
  throw error;
@@ -27687,7 +27690,12 @@ var ObservationStep = class {
27687
27690
  currentModel: this.turn.actorModelContext,
27688
27691
  requestContext: this.turn.requestContext,
27689
27692
  observabilityContext: this.turn.observabilityContext,
27690
- lastActivityAt: getLastActivityFromMessages(messageList.get.all.db())
27693
+ lastActivityAt: getLastActivityFromMessages(messageList.get.all.db()),
27694
+ reflectionHooks: om.composeHooks(void 0, {
27695
+ threadId,
27696
+ resourceId,
27697
+ trigger: "turn-sync"
27698
+ })
27691
27699
  });
27692
27700
  await this.turn.refreshRecord();
27693
27701
  if (this.turn.record.generationCount > preReflectGeneration) reflected = true;
@@ -27847,7 +27855,12 @@ var ObservationStep = class {
27847
27855
  currentModel: this.turn.actorModelContext,
27848
27856
  requestContext: this.turn.requestContext,
27849
27857
  observabilityContext: this.turn.observabilityContext,
27850
- lastActivityAt: getLastActivityFromMessages(messageList.get.all.db())
27858
+ lastActivityAt: getLastActivityFromMessages(messageList.get.all.db()),
27859
+ reflectionHooks: om.composeHooks(void 0, {
27860
+ threadId,
27861
+ resourceId,
27862
+ trigger: "turn-sync"
27863
+ })
27851
27864
  });
27852
27865
  return {
27853
27866
  succeeded: true,
@@ -27860,6 +27873,7 @@ var ObservationStep = class {
27860
27873
  threadId,
27861
27874
  resourceId,
27862
27875
  messages: messageList.get.all.db(),
27876
+ trigger: "turn-sync",
27863
27877
  requestContext: this.turn.requestContext,
27864
27878
  writer: this.turn.writer,
27865
27879
  observabilityContext: this.turn.observabilityContext
@@ -28685,12 +28699,16 @@ var ReflectorRunner = class {
28685
28699
  });
28686
28700
  reflectionHooks?.onReflectionStart?.();
28687
28701
  const asyncOp = this.doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal).then((outcome) => {
28688
- reflectionHooks?.onReflectionEnd?.({
28689
- usage: outcome?.usage,
28690
- ...outcome?.providerMetadata ? { providerMetadata: outcome.providerMetadata } : {}
28691
- });
28692
- }).catch(async (error) => {
28693
- if (writer) {
28702
+ try {
28703
+ reflectionHooks?.onReflectionEnd?.({
28704
+ usage: outcome?.usage,
28705
+ ...outcome?.providerMetadata ? { providerMetadata: outcome.providerMetadata } : {}
28706
+ });
28707
+ } catch (hookError) {
28708
+ omError("[OM] onReflectionEnd hook failed after async buffered reflection", hookError);
28709
+ }
28710
+ }, async (error) => {
28711
+ if (writer) try {
28694
28712
  const failedMarker = createBufferingFailedMarker({
28695
28713
  cycleId: `reflect-buf-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
28696
28714
  operationType: "reflection",
@@ -28705,12 +28723,18 @@ var ReflectorRunner = class {
28705
28723
  transient: true
28706
28724
  }).catch(() => {});
28707
28725
  await this.persistMarkerToStorage(failedMarker, record.threadId ?? "", record.resourceId ?? void 0);
28726
+ } catch (markerError) {
28727
+ omError("[OM] Failed to persist buffering-failed marker after async buffered reflection failure", markerError);
28708
28728
  }
28709
28729
  omError("[OM] Async buffered reflection failed", error);
28710
- reflectionHooks?.onReflectionEnd?.({
28711
- usage: void 0,
28712
- error: error instanceof Error ? error : new Error(String(error))
28713
- });
28730
+ try {
28731
+ reflectionHooks?.onReflectionEnd?.({
28732
+ usage: void 0,
28733
+ error: error instanceof Error ? error : new Error(String(error))
28734
+ });
28735
+ } catch (hookError) {
28736
+ omError("[OM] onReflectionEnd hook failed after async buffered reflection failure", hookError);
28737
+ }
28714
28738
  BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
28715
28739
  }).finally(() => {
28716
28740
  BufferingCoordinator.asyncBufferingOps.delete(bufferKey);
@@ -28957,7 +28981,6 @@ var ReflectorRunner = class {
28957
28981
  return;
28958
28982
  }
28959
28983
  }
28960
- reflectionHooks?.onReflectionStart?.();
28961
28984
  await this.storage.setReflectingFlag(record.id, true);
28962
28985
  registerOp(record.id, "reflecting");
28963
28986
  const cycleId = crypto.randomUUID();
@@ -28998,6 +29021,7 @@ var ReflectorRunner = class {
28998
29021
  let reflectionUsage;
28999
29022
  let reflectionProviderMetadata;
29000
29023
  let reflectionError;
29024
+ reflectionHooks?.onReflectionStart?.();
29001
29025
  try {
29002
29026
  const compressionStartLevel = await this.getCompressionStartLevel(requestContext);
29003
29027
  const reflectResult = await this.call(record.activeObservations, void 0, streamContext, reflectThreshold, abortSignal, void 0, compressionStartLevel, requestContext, priorExtractedValues, observabilityContext, void 0, mainAgent, sendSignal);
@@ -29061,12 +29085,15 @@ var ReflectorRunner = class {
29061
29085
  omError("[OM] Reflection failed", error);
29062
29086
  } finally {
29063
29087
  await this.storage.setReflectingFlag(record.id, false);
29064
- reflectionHooks?.onReflectionEnd?.({
29065
- usage: reflectionUsage,
29066
- error: reflectionError,
29067
- ...reflectionProviderMetadata ? { providerMetadata: reflectionProviderMetadata } : {}
29068
- });
29069
- unregisterOp(record.id, "reflecting");
29088
+ try {
29089
+ reflectionHooks?.onReflectionEnd?.({
29090
+ usage: reflectionUsage,
29091
+ error: reflectionError,
29092
+ ...reflectionProviderMetadata ? { providerMetadata: reflectionProviderMetadata } : {}
29093
+ });
29094
+ } finally {
29095
+ unregisterOp(record.id, "reflecting");
29096
+ }
29070
29097
  }
29071
29098
  }
29072
29099
  };
@@ -29515,6 +29542,8 @@ var ObservationalMemory = class ObservationalMemory {
29515
29542
  reflectionConfig;
29516
29543
  onDebugEvent;
29517
29544
  onIndexObservations;
29545
+ /** Config-level lifecycle hooks fired for every observation/reflection cycle. */
29546
+ hooks;
29518
29547
  /** Observer agent runner — handles LLM calls for extracting observations. */
29519
29548
  observer;
29520
29549
  /** Reflector agent runner — handles LLM calls for compressing observations. */
@@ -29575,6 +29604,7 @@ var ObservationalMemory = class ObservationalMemory {
29575
29604
  this.scope = config.scope ?? "thread";
29576
29605
  this.retrieval = Boolean(config.retrieval);
29577
29606
  this.onIndexObservations = config.onIndexObservations;
29607
+ this.hooks = config.hooks;
29578
29608
  this.mastra = config.mastra;
29579
29609
  this.memory = config.memory;
29580
29610
  const resolveModel = (model, defaultModel) => model === "default" ? defaultModel : model;
@@ -30496,7 +30526,11 @@ ${formattedMessages}
30496
30526
  transient: true
30497
30527
  }).catch(() => {});
30498
30528
  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(",")}`);
30499
- await ObservationStrategy.create(this, {
30529
+ await this.runBufferedObservationCycle({
30530
+ threadId,
30531
+ resourceId: freshRecord.resourceId ?? void 0,
30532
+ trigger: "async-buffer"
30533
+ }, () => ObservationStrategy.create(this, {
30500
30534
  record: freshRecord,
30501
30535
  threadId,
30502
30536
  resourceId: freshRecord.resourceId ?? void 0,
@@ -30506,7 +30540,7 @@ ${formattedMessages}
30506
30540
  writer,
30507
30541
  requestContext,
30508
30542
  observabilityContext
30509
- }).run();
30543
+ }).run());
30510
30544
  const maxTs = this.getMaxMessageTimestamp(messagesToBuffer);
30511
30545
  const cursor = new Date(maxTs.getTime() + 1);
30512
30546
  BufferingCoordinator.lastBufferedAtTime.set(bufferKey, cursor);
@@ -31079,7 +31113,11 @@ ${formattedMessages}
31079
31113
  ...startMarker,
31080
31114
  transient: true
31081
31115
  }).catch(() => {});
31082
- await ObservationStrategy.create(this, {
31116
+ await this.runBufferedObservationCycle({
31117
+ threadId,
31118
+ resourceId: record.resourceId ?? resourceId,
31119
+ trigger: "async-buffer"
31120
+ }, () => ObservationStrategy.create(this, {
31083
31121
  record,
31084
31122
  threadId,
31085
31123
  resourceId: record.resourceId ?? void 0,
@@ -31092,7 +31130,7 @@ ${formattedMessages}
31092
31130
  requestContext,
31093
31131
  currentModel: opts.currentModel,
31094
31132
  observabilityContext
31095
- }).run();
31133
+ }).run());
31096
31134
  if (isOmReproCaptureEnabled()) writeObserverExchangeReproCapture({
31097
31135
  threadId,
31098
31136
  resourceId: record.resourceId ?? void 0,
@@ -31302,6 +31340,88 @@ ${formattedMessages}
31302
31340
  };
31303
31341
  }
31304
31342
  /**
31343
+ * Compose the config-level hooks with optional per-call hooks into a single
31344
+ * `ObserveHooks` object, binding call context onto the config-level
31345
+ * callbacks. Config-level hooks are guarded so a throwing consumer hook can
31346
+ * never fail an observation/reflection cycle; per-call hooks keep their
31347
+ * existing payloads and propagation semantics. Returns undefined when
31348
+ * neither is configured, so call sites stay zero-cost.
31349
+ *
31350
+ * Used internally by every pipeline path (manual observe/reflect,
31351
+ * turn-engine sync observation, async buffering); public only so the
31352
+ * observation turn engine can thread config-level reflection hooks into
31353
+ * reflector calls.
31354
+ *
31355
+ * @internal
31356
+ */
31357
+ composeHooks(callHooks, context) {
31358
+ const configHooks = this.hooks;
31359
+ if (!configHooks) return callHooks;
31360
+ if (!callHooks && !Object.keys(configHooks).length) return void 0;
31361
+ const fireConfigHook = (name, arg) => {
31362
+ const hook = configHooks[name];
31363
+ if (!hook) return;
31364
+ const logHookFailure = (error) => omDebug(`[OM:hooks] config-level ${name} hook failed: ${error instanceof Error ? error.message : String(error)}`);
31365
+ try {
31366
+ const out = hook(arg);
31367
+ if (out && typeof out.then === "function") out.then(void 0, logHookFailure);
31368
+ } catch (error) {
31369
+ logHookFailure(error);
31370
+ }
31371
+ };
31372
+ return {
31373
+ onObservationStart: () => {
31374
+ fireConfigHook("onObservationStart", context);
31375
+ callHooks?.onObservationStart?.();
31376
+ },
31377
+ onObservationEnd: (result) => {
31378
+ fireConfigHook("onObservationEnd", {
31379
+ ...context,
31380
+ ...result
31381
+ });
31382
+ callHooks?.onObservationEnd?.(result);
31383
+ },
31384
+ onReflectionStart: () => {
31385
+ fireConfigHook("onReflectionStart", context);
31386
+ callHooks?.onReflectionStart?.();
31387
+ },
31388
+ onReflectionEnd: (result) => {
31389
+ fireConfigHook("onReflectionEnd", {
31390
+ ...context,
31391
+ ...result
31392
+ });
31393
+ callHooks?.onReflectionEnd?.(result);
31394
+ }
31395
+ };
31396
+ }
31397
+ /**
31398
+ * Run one buffered observation cycle, firing config-level hooks around it.
31399
+ * Shared by both async-buffer lanes — buffer() and
31400
+ * runAsyncBufferedObservation() — whose fire-and-forget callers never see
31401
+ * the strategy result. The async-buffer strategy swallows failures
31402
+ * (rethrowOnFailure=false) and surfaces them on the result instead, so the
31403
+ * end hook reports `error` for failed cycles even though nothing throws.
31404
+ */
31405
+ async runBufferedObservationCycle(context, run) {
31406
+ const hooks = this.composeHooks(void 0, context);
31407
+ hooks?.onObservationStart?.();
31408
+ let runResult;
31409
+ let runError;
31410
+ try {
31411
+ runResult = await run();
31412
+ return runResult;
31413
+ } catch (error) {
31414
+ runError = error instanceof Error ? error : new Error(String(error));
31415
+ throw error;
31416
+ } finally {
31417
+ hooks?.onObservationEnd?.({
31418
+ usage: runResult?.usage,
31419
+ error: runError ?? runResult?.error,
31420
+ ...runResult?.providerMetadata ? { providerMetadata: runResult.providerMetadata } : {}
31421
+ });
31422
+ }
31423
+ }
31424
+ /**
31305
31425
  * Manually trigger observation.
31306
31426
  *
31307
31427
  * When `messages` is provided, those are used directly (filtered for unobserved)
@@ -31312,8 +31432,13 @@ ${formattedMessages}
31312
31432
  * along with the updated record.
31313
31433
  */
31314
31434
  async observe(opts) {
31315
- const { threadId, resourceId, messages, hooks, requestContext } = opts;
31435
+ const { threadId, resourceId, messages, requestContext } = opts;
31316
31436
  const lockKey = this.buffering.getLockKey(threadId, resourceId);
31437
+ const hooks = this.composeHooks(opts.hooks, {
31438
+ threadId,
31439
+ resourceId,
31440
+ trigger: opts.trigger ?? "manual"
31441
+ });
31317
31442
  const reflectionHooks = hooks ? {
31318
31443
  onReflectionStart: hooks.onReflectionStart,
31319
31444
  onReflectionEnd: hooks.onReflectionEnd
@@ -31386,6 +31511,15 @@ ${formattedMessages}
31386
31511
  };
31387
31512
  await this.storage.setReflectingFlag(record.id, true);
31388
31513
  registerOp(record.id, "reflecting");
31514
+ const hooks = this.composeHooks(void 0, {
31515
+ threadId,
31516
+ resourceId,
31517
+ trigger: "manual"
31518
+ });
31519
+ hooks?.onReflectionStart?.();
31520
+ let reflectionUsage;
31521
+ let reflectionProviderMetadata;
31522
+ let reflectionError;
31389
31523
  try {
31390
31524
  const thread = await this.storage.getThreadById({ threadId });
31391
31525
  const previousOmMetadata = getThreadOMMetadata(thread?.metadata);
@@ -31415,12 +31549,16 @@ ${formattedMessages}
31415
31549
  metadata: newMetadata
31416
31550
  });
31417
31551
  }
31552
+ const updatedRecord = await this.getOrCreateRecord(threadId, resourceId);
31553
+ reflectionUsage = reflectResult.usage;
31554
+ reflectionProviderMetadata = reflectResult.providerMetadata;
31418
31555
  return {
31419
31556
  reflected: true,
31420
- record: await this.getOrCreateRecord(threadId, resourceId),
31557
+ record: updatedRecord,
31421
31558
  usage: reflectResult.usage
31422
31559
  };
31423
31560
  } catch (error) {
31561
+ reflectionError = error instanceof Error ? error : new Error(String(error));
31424
31562
  omError("[OM] reflect() failed", error);
31425
31563
  return {
31426
31564
  reflected: false,
@@ -31428,6 +31566,11 @@ ${formattedMessages}
31428
31566
  usage: void 0
31429
31567
  };
31430
31568
  } finally {
31569
+ hooks?.onReflectionEnd?.({
31570
+ usage: reflectionUsage,
31571
+ error: reflectionError,
31572
+ ...reflectionProviderMetadata ? { providerMetadata: reflectionProviderMetadata } : {}
31573
+ });
31431
31574
  await this.storage.setReflectingFlag(record.id, false);
31432
31575
  unregisterOp(record.id, "reflecting");
31433
31576
  }
@@ -32994,6 +33137,7 @@ ${workingMemory}`;
32994
33137
  model: omConfig.model,
32995
33138
  mastra: this._mastraInstance,
32996
33139
  onIndexObservations,
33140
+ hooks: omConfig.hooks,
32997
33141
  observation: omConfig.observation ? {
32998
33142
  model: omConfig.observation.model,
32999
33143
  messageTokens: omConfig.observation.messageTokens,
@@ -44282,4 +44426,4 @@ const agentBuilderWorkflows = {
44282
44426
  //#endregion
44283
44427
  export { agentBuilderWorkflows };
44284
44428
 
44285
- //# sourceMappingURL=dist-CgHgmUmP.js.map
44429
+ //# sourceMappingURL=dist-CagLZOyx.js.map