@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.
@@ -39704,12 +39704,25 @@ function getOmObservabilityContext(args) {
39704
39704
  metrics: args.metrics
39705
39705
  };
39706
39706
  }
39707
- /** Key used to store gateway detection result in per-processor state. */
39708
- const GATEWAY_STATE_KEY = "__isGatewayModel";
39707
+ /** Key used to store whether the gateway manages memory for the current step in per-processor state. */
39708
+ const GATEWAY_STATE_KEY = "__isGatewayMemoryManaged";
39709
39709
  /** Step number OM last recovered from a context-overflow error, so each step retries at most once. */
39710
39710
  const CONTEXT_OVERFLOW_STEP_KEY = "__omContextOverflowStep";
39711
- /** Check if the model is routed through a Mastra gateway (duck-type check to avoid cross-package instanceof issues). */
39712
- function isMastraGatewayModel(model) {
39711
+ /**
39712
+ * Whether the Mastra gateway serves Observational Memory for this step's model.
39713
+ *
39714
+ * Gateway models only get memory from the gateway when the credential is a Gateway project
39715
+ * key. Organization keys (`msk-gateway-…`, `mskv2_…`) are served by a gateway without the
39716
+ * memory API, so memory has to stay local. Newer `@mastra/core` exposes that decision on the
39717
+ * router model; when it is absent (older core, or a plain model) fall back to the historical
39718
+ * `mastra/` prefix check so gateway-side memory is never double-processed.
39719
+ *
39720
+ * A model that fails the check is not treated as local. Core answers `false` only for a model
39721
+ * that isn't on the gateway, and throws when the credential can't be resolved — including when it
39722
+ * is missing; letting that through keeps the two sides in agreement.
39723
+ */
39724
+ async function isGatewayMemoryManaged(model) {
39725
+ if (typeof model === "object" && model !== null && typeof model.isGatewayMemoryManaged === "function") return Boolean(await model.isGatewayMemoryManaged());
39713
39726
  return typeof model === "object" && model !== null && "gatewayId" in model && model.gatewayId === "mastra";
39714
39727
  }
39715
39728
  function injectObservationContextMessages({ messageList, systemMessages, continuationMessage, hasObservations, threadId, resourceId }) {
@@ -39775,6 +39788,34 @@ var ObservationalMemoryProcessor = class {
39775
39788
  this.memory = memory;
39776
39789
  this.temporalMarkers = options?.temporalMarkers ?? false;
39777
39790
  }
39791
+ /**
39792
+ * End any locally started turn without leaving it dangling.
39793
+ *
39794
+ * A gateway-managed step short-circuits both processor phases, so a turn started on an
39795
+ * earlier step of the same run — a delegation run whose model changed, or a run whose key
39796
+ * changed — would otherwise never be ended and its messages never persisted. `end()` with
39797
+ * no arguments flushes what the turn already tracked; finalization passes the accepted
39798
+ * terminal list for the same reason the regular output path does.
39799
+ *
39800
+ * A rejected write is not swallowed. `end()` marks the turn ended before it persists, so a
39801
+ * failed write leaves the turn unusable and its messages would be lost silently while the run
39802
+ * reported success. The drain persists those messages directly and rethrows, so a storage
39803
+ * failure surfaces instead of dropping the turn.
39804
+ */
39805
+ async endActiveTurn(state, messageList) {
39806
+ const activeTurn = asLiveTurn(state.__omTurn) ?? this.turn;
39807
+ this.turn = void 0;
39808
+ state.__omTurn = void 0;
39809
+ if (!activeTurn || activeTurn.ended) return;
39810
+ const terminalList = messageList ?? activeTurn.messageList;
39811
+ const unsavedMessages = [...terminalList.get.input.db(), ...terminalList.get.response.db()];
39812
+ try {
39813
+ await activeTurn.end(terminalList);
39814
+ } catch (error) {
39815
+ if (unsavedMessages.length > 0) await this.engine.persistMessages(unsavedMessages, activeTurn.threadId, activeTurn.resourceId).catch(() => {});
39816
+ throw error;
39817
+ }
39818
+ }
39778
39819
  async processInputStep(args) {
39779
39820
  const { messageList, requestContext, stepNumber, state: _state, writer, model, abortSignal, abort, messageId, rotateResponseMessageId } = args;
39780
39821
  const state = _state ?? {};
@@ -39784,9 +39825,11 @@ var ObservationalMemoryProcessor = class {
39784
39825
  omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null — returning early`);
39785
39826
  return messageList;
39786
39827
  }
39787
- if (isMastraGatewayModel(model)) {
39788
- state[GATEWAY_STATE_KEY] = true;
39789
- omDebug(`[OM:processInputStep:GATEWAY] gateway handles OM — skipping local processing`);
39828
+ const gatewayMemoryManaged = await isGatewayMemoryManaged(model);
39829
+ state[GATEWAY_STATE_KEY] = gatewayMemoryManaged;
39830
+ if (gatewayMemoryManaged) {
39831
+ await this.endActiveTurn(state);
39832
+ omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory — skipping local processing`);
39790
39833
  return messageList;
39791
39834
  }
39792
39835
  const { threadId, resourceId } = context;
@@ -39976,7 +40019,10 @@ var ObservationalMemoryProcessor = class {
39976
40019
  const state = _state ?? {};
39977
40020
  const context = this.engine.getThreadContext(requestContext, messageList);
39978
40021
  if (!context) return messageList;
39979
- if (state[GATEWAY_STATE_KEY]) return messageList;
40022
+ if (state[GATEWAY_STATE_KEY]) {
40023
+ await this.endActiveTurn(state, messageList.cloneForPersistence());
40024
+ return messageList;
40025
+ }
39980
40026
  state.__omObservabilityContext = getOmObservabilityContext(args);
39981
40027
  return this.engine.getTokenCounter().runWithModelContext(state.__omActorModelContext, async () => {
39982
40028
  if (parseMemoryRequestContext(requestContext)?.memoryConfig?.readOnly) return messageList;
@@ -40498,7 +40544,7 @@ var Memory = class Memory extends MastraMemory {
40498
40544
  }
40499
40545
  }
40500
40546
  const threshold = (typeof config.semanticRecall === "object" ? config.semanticRecall : void 0)?.threshold;
40501
- const filteredVectorResults = threshold !== void 0 ? vectorResults.filter((r) => r.score >= threshold) : vectorResults;
40547
+ const filteredVectorResults = vectorResults.filter((r) => (threshold === void 0 || r.score >= threshold) && (resourceScope ? r.metadata?.resource_id === resourceId : r.metadata?.thread_id === threadId));
40502
40548
  const memoryStore = await this.getMemoryStore();
40503
40549
  const include = filteredVectorResults.map((r) => ({
40504
40550
  id: r.metadata?.message_id,
@@ -40562,6 +40608,7 @@ var Memory = class Memory extends MastraMemory {
40562
40608
  rawMessages = shouldGetNewestAndReverse ? paginatedResult.messages.reverse() : paginatedResult.messages;
40563
40609
  ({total, page: resultPage, perPage: resultPerPage, hasMore} = paginatedResult);
40564
40610
  }
40611
+ if (include.length) rawMessages = rawMessages.filter((message) => message.threadId === threadId || resourceScope && message.resourceId === resourceId);
40565
40612
  const messages = filterSystemReminderMessages(new MessageList({
40566
40613
  threadId,
40567
40614
  resourceId
@@ -40912,42 +40959,74 @@ ${workingMemory}`;
40912
40959
  this.embeddingCache.set(key, result);
40913
40960
  return result;
40914
40961
  }
40962
+ chunkEmbeddingCache = new LRUCache({ max: DEFAULT_EMBEDDING_CACHE_MAX_SIZE });
40963
+ chunkEmbeddingCacheOwner = {};
40964
+ /**
40965
+ * Embeds one message's chunks, reusing vectors already produced for the same chunks. Usage is
40966
+ * returned only for a call that reached the embedder.
40967
+ */
40968
+ async embedMessageChunks(chunks) {
40969
+ const producer = {
40970
+ embedder: this.embedder,
40971
+ embedderOptions: this.embedderOptions
40972
+ };
40973
+ const key = (await this.hasher).h64(JSON.stringify(chunks));
40974
+ if (producer.embedder !== this.embedder || producer.embedderOptions !== this.embedderOptions) return this.embedValues(chunks, producer);
40975
+ const owner = this.chunkEmbeddingCacheOwner;
40976
+ if (owner.embedder !== producer.embedder || owner.embedderOptions !== producer.embedderOptions) {
40977
+ this.chunkEmbeddingCache.clear();
40978
+ this.chunkEmbeddingCacheOwner = producer;
40979
+ }
40980
+ const cached = this.chunkEmbeddingCache.get(key);
40981
+ if (cached) return { embeddings: await cached };
40982
+ const result = this.embedValues(chunks, producer);
40983
+ const embeddings = result.then(({ embeddings }) => {
40984
+ if (embeddings.length !== chunks.length) evict();
40985
+ return embeddings;
40986
+ });
40987
+ const evict = () => {
40988
+ if (this.chunkEmbeddingCache.get(key) === embeddings) this.chunkEmbeddingCache.delete(key);
40989
+ };
40990
+ embeddings.catch(evict);
40991
+ this.chunkEmbeddingCache.set(key, embeddings);
40992
+ return result;
40993
+ }
40915
40994
  /** Sends texts to the embedder through the AI SDK version that matches its spec. */
40916
- async embedValues(values) {
40917
- if (typeof this.embedder === `undefined`) throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
40918
- const isFastEmbed = this.embedder.provider === `fastembed`;
40995
+ async embedValues(values, { embedder, embedderOptions } = this) {
40996
+ if (typeof embedder === `undefined`) throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
40997
+ const isFastEmbed = embedder.provider === `fastembed`;
40919
40998
  if (isFastEmbed && this.firstEmbed instanceof Promise) await this.firstEmbed;
40920
40999
  const options = {
40921
41000
  values,
40922
41001
  maxRetries: 3
40923
41002
  };
40924
- const model = this.embedder;
41003
+ const model = embedder;
40925
41004
  let promise;
40926
41005
  switch (model.specificationVersion) {
40927
41006
  case "v4":
40928
41007
  promise = embedMany({
40929
41008
  ...options,
40930
- ...this.embedderOptions,
41009
+ ...embedderOptions,
40931
41010
  model
40932
41011
  });
40933
41012
  break;
40934
41013
  case "v3":
40935
41014
  promise = embedMany$1({
40936
41015
  ...options,
40937
- ...this.embedderOptions,
41016
+ ...embedderOptions,
40938
41017
  model
40939
41018
  });
40940
41019
  break;
40941
41020
  case "v2":
40942
41021
  promise = embedMany$2({
40943
41022
  ...options,
40944
- ...this.embedderOptions,
41023
+ ...embedderOptions,
40945
41024
  model
40946
41025
  });
40947
41026
  break;
40948
41027
  default: promise = embedMany$3({
40949
41028
  ...options,
40950
- ...this.embedderOptions,
41029
+ ...embedderOptions,
40951
41030
  model
40952
41031
  });
40953
41032
  }
@@ -40989,7 +41068,7 @@ ${workingMemory}`;
40989
41068
  if (!this.embedder && !this.isSelfEmbedding) throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
40990
41069
  return buildMessageEmbeddingRows({
40991
41070
  items,
40992
- embed: this.isSelfEmbedding ? void 0 : (chunks) => this.embedValues(chunks),
41071
+ embed: this.isSelfEmbedding ? void 0 : (chunks) => this.embedMessageChunks(chunks),
40993
41072
  maxChunkChars: resolveMaxChunkChars({
40994
41073
  maxChunkChars: this.configuredMaxChunkChars,
40995
41074
  embedder: this.embedder
@@ -41575,6 +41654,7 @@ Notes:
41575
41654
  });
41576
41655
  for (const r of results) {
41577
41656
  if (!r.metadata?.thread_id) continue;
41657
+ if (r.metadata.resource_id !== resourceId || filter?.threadId && r.metadata.thread_id !== filter.threadId) continue;
41578
41658
  const groupId = typeof r.metadata.group_id === "string" ? r.metadata.group_id : void 0;
41579
41659
  if (!groupId) continue;
41580
41660
  queryResults.push({
@@ -42515,4 +42595,4 @@ Notes:
42515
42595
  };
42516
42596
  export { summarizeConversation as A, injectAnchorIds as B, wrapInObservationGroup as C, WorkingMemoryExtractor as D, Subconscious as E, extractCurrentTask as F, OBSERVATION_CONTEXT_INSTRUCTIONS as G, stripEphemeralAnchorIds as H, formatMessagesForObserver as I, OBSERVATION_CONTINUATION_HINT as J, OBSERVATION_CONTEXT_PROMPT as K, hasCurrentTaskSection as L, OBSERVER_SYSTEM_PROMPT as M, buildObserverPrompt as N, deepMergeWorkingMemory as O, buildObserverSystemPrompt as P, optimizeObservationsForContext as R, stripObservationGroups as S, StaleKnowledgeSemanticIndexError as T, Extractor as U, parseAnchorId as V, OBSERVATIONAL_MEMORY_DEFAULTS as W, getObservationContextPrompt as Y, combineObservationGroupRanges as _, extractWorkingMemoryContent as a, reconcileObservationGroupsFromReflection as b, getObservationsAsOf as c, AUTO_MODEL_BY_PROVIDER as d, resolveAutoModelId as f, ModelByInputTokens as g, WorkingMemoryStateProcessor as h, WorkingMemory as i, TokenCounter as j, SUMMARIZE_THREAD_DEFAULTS as k, ObservationalMemoryProcessor as l, WORKING_MEMORY_STATE_PROCESSOR_ID as m, MessageHistory$1 as n, extractWorkingMemoryTags as o, WORKING_MEMORY_STATE_ID as p, OBSERVATION_CONTEXT_PROMPT_THREAD as q, SemanticRecall as r, removeWorkingMemoryTags as s, Memory as t, ObservationalMemory as u, deriveObservationGroupProvenance as v, KnowledgeSemanticIndexCoordinator as w, renderObservationGroupsForReflection as x, parseObservationGroups as y, parseObserverOutput as z };
42517
42597
 
42518
- //# sourceMappingURL=src-DGBUSKXy.js.map
42598
+ //# sourceMappingURL=src-Xhctgeae.js.map