@mastra/memory 1.41.2-alpha.1 → 1.41.2-alpha.2

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.
@@ -39725,12 +39725,25 @@ function getOmObservabilityContext(args) {
39725
39725
  metrics: args.metrics
39726
39726
  };
39727
39727
  }
39728
- /** Key used to store gateway detection result in per-processor state. */
39729
- const GATEWAY_STATE_KEY = "__isGatewayModel";
39728
+ /** Key used to store whether the gateway manages memory for the current step in per-processor state. */
39729
+ const GATEWAY_STATE_KEY = "__isGatewayMemoryManaged";
39730
39730
  /** Step number OM last recovered from a context-overflow error, so each step retries at most once. */
39731
39731
  const CONTEXT_OVERFLOW_STEP_KEY = "__omContextOverflowStep";
39732
- /** Check if the model is routed through a Mastra gateway (duck-type check to avoid cross-package instanceof issues). */
39733
- function isMastraGatewayModel(model) {
39732
+ /**
39733
+ * Whether the Mastra gateway serves Observational Memory for this step's model.
39734
+ *
39735
+ * Gateway models only get memory from the gateway when the credential is a Gateway project
39736
+ * key. Organization keys (`msk-gateway-…`, `mskv2_…`) are served by a gateway without the
39737
+ * memory API, so memory has to stay local. Newer `@mastra/core` exposes that decision on the
39738
+ * router model; when it is absent (older core, or a plain model) fall back to the historical
39739
+ * `mastra/` prefix check so gateway-side memory is never double-processed.
39740
+ *
39741
+ * A model that fails the check is not treated as local. Core answers `false` only for a model
39742
+ * that isn't on the gateway, and throws when the credential can't be resolved — including when it
39743
+ * is missing; letting that through keeps the two sides in agreement.
39744
+ */
39745
+ async function isGatewayMemoryManaged(model) {
39746
+ if (typeof model === "object" && model !== null && typeof model.isGatewayMemoryManaged === "function") return Boolean(await model.isGatewayMemoryManaged());
39734
39747
  return typeof model === "object" && model !== null && "gatewayId" in model && model.gatewayId === "mastra";
39735
39748
  }
39736
39749
  function injectObservationContextMessages({ messageList, systemMessages, continuationMessage, hasObservations, threadId, resourceId }) {
@@ -39796,6 +39809,34 @@ var ObservationalMemoryProcessor = class {
39796
39809
  this.memory = memory;
39797
39810
  this.temporalMarkers = options?.temporalMarkers ?? false;
39798
39811
  }
39812
+ /**
39813
+ * End any locally started turn without leaving it dangling.
39814
+ *
39815
+ * A gateway-managed step short-circuits both processor phases, so a turn started on an
39816
+ * earlier step of the same run — a delegation run whose model changed, or a run whose key
39817
+ * changed — would otherwise never be ended and its messages never persisted. `end()` with
39818
+ * no arguments flushes what the turn already tracked; finalization passes the accepted
39819
+ * terminal list for the same reason the regular output path does.
39820
+ *
39821
+ * A rejected write is not swallowed. `end()` marks the turn ended before it persists, so a
39822
+ * failed write leaves the turn unusable and its messages would be lost silently while the run
39823
+ * reported success. The drain persists those messages directly and rethrows, so a storage
39824
+ * failure surfaces instead of dropping the turn.
39825
+ */
39826
+ async endActiveTurn(state, messageList) {
39827
+ const activeTurn = asLiveTurn(state.__omTurn) ?? this.turn;
39828
+ this.turn = void 0;
39829
+ state.__omTurn = void 0;
39830
+ if (!activeTurn || activeTurn.ended) return;
39831
+ const terminalList = messageList ?? activeTurn.messageList;
39832
+ const unsavedMessages = [...terminalList.get.input.db(), ...terminalList.get.response.db()];
39833
+ try {
39834
+ await activeTurn.end(terminalList);
39835
+ } catch (error) {
39836
+ if (unsavedMessages.length > 0) await this.engine.persistMessages(unsavedMessages, activeTurn.threadId, activeTurn.resourceId).catch(() => {});
39837
+ throw error;
39838
+ }
39839
+ }
39799
39840
  async processInputStep(args) {
39800
39841
  const { messageList, requestContext, stepNumber, state: _state, writer, model, abortSignal, abort, messageId, rotateResponseMessageId } = args;
39801
39842
  const state = _state ?? {};
@@ -39805,9 +39846,11 @@ var ObservationalMemoryProcessor = class {
39805
39846
  omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null — returning early`);
39806
39847
  return messageList;
39807
39848
  }
39808
- if (isMastraGatewayModel(model)) {
39809
- state[GATEWAY_STATE_KEY] = true;
39810
- omDebug(`[OM:processInputStep:GATEWAY] gateway handles OM — skipping local processing`);
39849
+ const gatewayMemoryManaged = await isGatewayMemoryManaged(model);
39850
+ state[GATEWAY_STATE_KEY] = gatewayMemoryManaged;
39851
+ if (gatewayMemoryManaged) {
39852
+ await this.endActiveTurn(state);
39853
+ omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory — skipping local processing`);
39811
39854
  return messageList;
39812
39855
  }
39813
39856
  const { threadId, resourceId } = context;
@@ -39997,7 +40040,10 @@ var ObservationalMemoryProcessor = class {
39997
40040
  const state = _state ?? {};
39998
40041
  const context = this.engine.getThreadContext(requestContext, messageList);
39999
40042
  if (!context) return messageList;
40000
- if (state[GATEWAY_STATE_KEY]) return messageList;
40043
+ if (state[GATEWAY_STATE_KEY]) {
40044
+ await this.endActiveTurn(state, messageList.cloneForPersistence());
40045
+ return messageList;
40046
+ }
40001
40047
  state.__omObservabilityContext = getOmObservabilityContext(args);
40002
40048
  return this.engine.getTokenCounter().runWithModelContext(state.__omActorModelContext, async () => {
40003
40049
  if ((0, _mastra_core_memory.parseMemoryRequestContext)(requestContext)?.memoryConfig?.readOnly) return messageList;
@@ -40519,7 +40565,7 @@ var Memory = class Memory extends _mastra_core_memory.MastraMemory {
40519
40565
  }
40520
40566
  }
40521
40567
  const threshold = (typeof config.semanticRecall === "object" ? config.semanticRecall : void 0)?.threshold;
40522
- const filteredVectorResults = threshold !== void 0 ? vectorResults.filter((r) => r.score >= threshold) : vectorResults;
40568
+ const filteredVectorResults = vectorResults.filter((r) => (threshold === void 0 || r.score >= threshold) && (resourceScope ? r.metadata?.resource_id === resourceId : r.metadata?.thread_id === threadId));
40523
40569
  const memoryStore = await this.getMemoryStore();
40524
40570
  const include = filteredVectorResults.map((r) => ({
40525
40571
  id: r.metadata?.message_id,
@@ -40583,6 +40629,7 @@ var Memory = class Memory extends _mastra_core_memory.MastraMemory {
40583
40629
  rawMessages = shouldGetNewestAndReverse ? paginatedResult.messages.reverse() : paginatedResult.messages;
40584
40630
  ({total, page: resultPage, perPage: resultPerPage, hasMore} = paginatedResult);
40585
40631
  }
40632
+ if (include.length) rawMessages = rawMessages.filter((message) => message.threadId === threadId || resourceScope && message.resourceId === resourceId);
40586
40633
  const messages = filterSystemReminderMessages(new _mastra_core_agent.MessageList({
40587
40634
  threadId,
40588
40635
  resourceId
@@ -40933,42 +40980,74 @@ ${workingMemory}`;
40933
40980
  this.embeddingCache.set(key, result);
40934
40981
  return result;
40935
40982
  }
40983
+ chunkEmbeddingCache = new lru_cache.LRUCache({ max: DEFAULT_EMBEDDING_CACHE_MAX_SIZE });
40984
+ chunkEmbeddingCacheOwner = {};
40985
+ /**
40986
+ * Embeds one message's chunks, reusing vectors already produced for the same chunks. Usage is
40987
+ * returned only for a call that reached the embedder.
40988
+ */
40989
+ async embedMessageChunks(chunks) {
40990
+ const producer = {
40991
+ embedder: this.embedder,
40992
+ embedderOptions: this.embedderOptions
40993
+ };
40994
+ const key = (await this.hasher).h64(JSON.stringify(chunks));
40995
+ if (producer.embedder !== this.embedder || producer.embedderOptions !== this.embedderOptions) return this.embedValues(chunks, producer);
40996
+ const owner = this.chunkEmbeddingCacheOwner;
40997
+ if (owner.embedder !== producer.embedder || owner.embedderOptions !== producer.embedderOptions) {
40998
+ this.chunkEmbeddingCache.clear();
40999
+ this.chunkEmbeddingCacheOwner = producer;
41000
+ }
41001
+ const cached = this.chunkEmbeddingCache.get(key);
41002
+ if (cached) return { embeddings: await cached };
41003
+ const result = this.embedValues(chunks, producer);
41004
+ const embeddings = result.then(({ embeddings }) => {
41005
+ if (embeddings.length !== chunks.length) evict();
41006
+ return embeddings;
41007
+ });
41008
+ const evict = () => {
41009
+ if (this.chunkEmbeddingCache.get(key) === embeddings) this.chunkEmbeddingCache.delete(key);
41010
+ };
41011
+ embeddings.catch(evict);
41012
+ this.chunkEmbeddingCache.set(key, embeddings);
41013
+ return result;
41014
+ }
40936
41015
  /** Sends texts to the embedder through the AI SDK version that matches its spec. */
40937
- async embedValues(values) {
40938
- if (typeof this.embedder === `undefined`) throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
40939
- const isFastEmbed = this.embedder.provider === `fastembed`;
41016
+ async embedValues(values, { embedder, embedderOptions } = this) {
41017
+ if (typeof embedder === `undefined`) throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
41018
+ const isFastEmbed = embedder.provider === `fastembed`;
40940
41019
  if (isFastEmbed && this.firstEmbed instanceof Promise) await this.firstEmbed;
40941
41020
  const options = {
40942
41021
  values,
40943
41022
  maxRetries: 3
40944
41023
  };
40945
- const model = this.embedder;
41024
+ const model = embedder;
40946
41025
  let promise;
40947
41026
  switch (model.specificationVersion) {
40948
41027
  case "v4":
40949
41028
  promise = embedMany({
40950
41029
  ...options,
40951
- ...this.embedderOptions,
41030
+ ...embedderOptions,
40952
41031
  model
40953
41032
  });
40954
41033
  break;
40955
41034
  case "v3":
40956
41035
  promise = embedMany$1({
40957
41036
  ...options,
40958
- ...this.embedderOptions,
41037
+ ...embedderOptions,
40959
41038
  model
40960
41039
  });
40961
41040
  break;
40962
41041
  case "v2":
40963
41042
  promise = embedMany$2({
40964
41043
  ...options,
40965
- ...this.embedderOptions,
41044
+ ...embedderOptions,
40966
41045
  model
40967
41046
  });
40968
41047
  break;
40969
41048
  default: promise = embedMany$3({
40970
41049
  ...options,
40971
- ...this.embedderOptions,
41050
+ ...embedderOptions,
40972
41051
  model
40973
41052
  });
40974
41053
  }
@@ -41010,7 +41089,7 @@ ${workingMemory}`;
41010
41089
  if (!this.embedder && !this.isSelfEmbedding) throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
41011
41090
  return (0, _mastra_core_memory.buildMessageEmbeddingRows)({
41012
41091
  items,
41013
- embed: this.isSelfEmbedding ? void 0 : (chunks) => this.embedValues(chunks),
41092
+ embed: this.isSelfEmbedding ? void 0 : (chunks) => this.embedMessageChunks(chunks),
41014
41093
  maxChunkChars: (0, _mastra_core_memory.resolveMaxChunkChars)({
41015
41094
  maxChunkChars: this.configuredMaxChunkChars,
41016
41095
  embedder: this.embedder
@@ -41596,6 +41675,7 @@ Notes:
41596
41675
  });
41597
41676
  for (const r of results) {
41598
41677
  if (!r.metadata?.thread_id) continue;
41678
+ if (r.metadata.resource_id !== resourceId || filter?.threadId && r.metadata.thread_id !== filter.threadId) continue;
41599
41679
  const groupId = typeof r.metadata.group_id === "string" ? r.metadata.group_id : void 0;
41600
41680
  if (!groupId) continue;
41601
41681
  queryResults.push({
@@ -42811,4 +42891,4 @@ Object.defineProperty(exports, "wrapInObservationGroup", {
42811
42891
  }
42812
42892
  });
42813
42893
 
42814
- //# sourceMappingURL=src-D49WAwNu.cjs.map
42894
+ //# sourceMappingURL=src-BLniLryu.cjs.map