@mastra/memory 1.41.2-alpha.0 → 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.
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +76 -76
- package/dist/docs/references/docs-memory-observational-memory.md +8 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/processors/index.cjs +1 -1
- package/dist/processors/index.js +1 -1
- package/dist/processors/observational-memory/processor.d.ts +15 -0
- package/dist/processors/observational-memory/processor.d.ts.map +1 -1
- package/dist/processors/observational-memory/token-counter.d.ts.map +1 -1
- package/dist/{src-C-vHUKMZ.cjs → src-BLniLryu.cjs} +115 -22
- package/dist/{src-C-vHUKMZ.cjs.map → src-BLniLryu.cjs.map} +1 -1
- package/dist/{src-CshY_uyn.js → src-Xhctgeae.js} +115 -22
- package/dist/{src-CshY_uyn.js.map → src-Xhctgeae.js.map} +1 -1
- package/package.json +2 -2
|
@@ -28079,6 +28079,19 @@ function buildEstimateKey(kind, text) {
|
|
|
28079
28079
|
function resolveEstimatorId() {
|
|
28080
28080
|
return "tokenx";
|
|
28081
28081
|
}
|
|
28082
|
+
const ATTACHMENT_CONTENT_PART_TYPES = /* @__PURE__ */ new Set([
|
|
28083
|
+
"image",
|
|
28084
|
+
"image-data",
|
|
28085
|
+
"media",
|
|
28086
|
+
"audio",
|
|
28087
|
+
"file-data"
|
|
28088
|
+
]);
|
|
28089
|
+
/** Mirrors the parts countMultimodalToolResultContent counts as attachments. */
|
|
28090
|
+
function isAttachmentContentPart(item) {
|
|
28091
|
+
if (!item || typeof item !== "object") return false;
|
|
28092
|
+
const contentPart = item;
|
|
28093
|
+
return ATTACHMENT_CONTENT_PART_TYPES.has(contentPart.type) && typeof contentPart.data === "string";
|
|
28094
|
+
}
|
|
28082
28095
|
function isTokenEstimateEntry(value) {
|
|
28083
28096
|
if (!value || typeof value !== "object") return false;
|
|
28084
28097
|
const entry = value;
|
|
@@ -28871,12 +28884,12 @@ var TokenCounter = class TokenCounter {
|
|
|
28871
28884
|
}
|
|
28872
28885
|
countMultimodalToolResultContent(part, toolResult) {
|
|
28873
28886
|
if (!toolResult || typeof toolResult !== "object") return;
|
|
28887
|
+
const output = toolResult;
|
|
28888
|
+
const content = output.type === "content" && Array.isArray(output.value) ? output.value : output.content;
|
|
28889
|
+
if (!Array.isArray(content) || !content.some(isAttachmentContentPart)) return;
|
|
28874
28890
|
const resultKey = buildEstimateKey("tool-result-multimodal-content-source", JSON.stringify(toolResult));
|
|
28875
28891
|
const cached = this.multimodalToolResultCounts.get(part);
|
|
28876
28892
|
if (cached?.resultKey === resultKey) return cached.tokens;
|
|
28877
|
-
const output = toolResult;
|
|
28878
|
-
const content = output.type === "content" && Array.isArray(output.value) ? output.value : output.content;
|
|
28879
|
-
if (!Array.isArray(content)) return;
|
|
28880
28893
|
let hasAttachment = false;
|
|
28881
28894
|
let tokens = 0;
|
|
28882
28895
|
const cacheParts = [];
|
|
@@ -39691,12 +39704,25 @@ function getOmObservabilityContext(args) {
|
|
|
39691
39704
|
metrics: args.metrics
|
|
39692
39705
|
};
|
|
39693
39706
|
}
|
|
39694
|
-
/** Key used to store gateway
|
|
39695
|
-
const GATEWAY_STATE_KEY = "
|
|
39707
|
+
/** Key used to store whether the gateway manages memory for the current step in per-processor state. */
|
|
39708
|
+
const GATEWAY_STATE_KEY = "__isGatewayMemoryManaged";
|
|
39696
39709
|
/** Step number OM last recovered from a context-overflow error, so each step retries at most once. */
|
|
39697
39710
|
const CONTEXT_OVERFLOW_STEP_KEY = "__omContextOverflowStep";
|
|
39698
|
-
/**
|
|
39699
|
-
|
|
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());
|
|
39700
39726
|
return typeof model === "object" && model !== null && "gatewayId" in model && model.gatewayId === "mastra";
|
|
39701
39727
|
}
|
|
39702
39728
|
function injectObservationContextMessages({ messageList, systemMessages, continuationMessage, hasObservations, threadId, resourceId }) {
|
|
@@ -39762,6 +39788,34 @@ var ObservationalMemoryProcessor = class {
|
|
|
39762
39788
|
this.memory = memory;
|
|
39763
39789
|
this.temporalMarkers = options?.temporalMarkers ?? false;
|
|
39764
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
|
+
}
|
|
39765
39819
|
async processInputStep(args) {
|
|
39766
39820
|
const { messageList, requestContext, stepNumber, state: _state, writer, model, abortSignal, abort, messageId, rotateResponseMessageId } = args;
|
|
39767
39821
|
const state = _state ?? {};
|
|
@@ -39771,9 +39825,11 @@ var ObservationalMemoryProcessor = class {
|
|
|
39771
39825
|
omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null — returning early`);
|
|
39772
39826
|
return messageList;
|
|
39773
39827
|
}
|
|
39774
|
-
|
|
39775
|
-
|
|
39776
|
-
|
|
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`);
|
|
39777
39833
|
return messageList;
|
|
39778
39834
|
}
|
|
39779
39835
|
const { threadId, resourceId } = context;
|
|
@@ -39963,7 +40019,10 @@ var ObservationalMemoryProcessor = class {
|
|
|
39963
40019
|
const state = _state ?? {};
|
|
39964
40020
|
const context = this.engine.getThreadContext(requestContext, messageList);
|
|
39965
40021
|
if (!context) return messageList;
|
|
39966
|
-
if (state[GATEWAY_STATE_KEY])
|
|
40022
|
+
if (state[GATEWAY_STATE_KEY]) {
|
|
40023
|
+
await this.endActiveTurn(state, messageList.cloneForPersistence());
|
|
40024
|
+
return messageList;
|
|
40025
|
+
}
|
|
39967
40026
|
state.__omObservabilityContext = getOmObservabilityContext(args);
|
|
39968
40027
|
return this.engine.getTokenCounter().runWithModelContext(state.__omActorModelContext, async () => {
|
|
39969
40028
|
if (parseMemoryRequestContext(requestContext)?.memoryConfig?.readOnly) return messageList;
|
|
@@ -40485,7 +40544,7 @@ var Memory = class Memory extends MastraMemory {
|
|
|
40485
40544
|
}
|
|
40486
40545
|
}
|
|
40487
40546
|
const threshold = (typeof config.semanticRecall === "object" ? config.semanticRecall : void 0)?.threshold;
|
|
40488
|
-
const filteredVectorResults =
|
|
40547
|
+
const filteredVectorResults = vectorResults.filter((r) => (threshold === void 0 || r.score >= threshold) && (resourceScope ? r.metadata?.resource_id === resourceId : r.metadata?.thread_id === threadId));
|
|
40489
40548
|
const memoryStore = await this.getMemoryStore();
|
|
40490
40549
|
const include = filteredVectorResults.map((r) => ({
|
|
40491
40550
|
id: r.metadata?.message_id,
|
|
@@ -40549,6 +40608,7 @@ var Memory = class Memory extends MastraMemory {
|
|
|
40549
40608
|
rawMessages = shouldGetNewestAndReverse ? paginatedResult.messages.reverse() : paginatedResult.messages;
|
|
40550
40609
|
({total, page: resultPage, perPage: resultPerPage, hasMore} = paginatedResult);
|
|
40551
40610
|
}
|
|
40611
|
+
if (include.length) rawMessages = rawMessages.filter((message) => message.threadId === threadId || resourceScope && message.resourceId === resourceId);
|
|
40552
40612
|
const messages = filterSystemReminderMessages(new MessageList({
|
|
40553
40613
|
threadId,
|
|
40554
40614
|
resourceId
|
|
@@ -40899,42 +40959,74 @@ ${workingMemory}`;
|
|
|
40899
40959
|
this.embeddingCache.set(key, result);
|
|
40900
40960
|
return result;
|
|
40901
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
|
+
}
|
|
40902
40994
|
/** Sends texts to the embedder through the AI SDK version that matches its spec. */
|
|
40903
|
-
async embedValues(values) {
|
|
40904
|
-
if (typeof
|
|
40905
|
-
const isFastEmbed =
|
|
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`;
|
|
40906
40998
|
if (isFastEmbed && this.firstEmbed instanceof Promise) await this.firstEmbed;
|
|
40907
40999
|
const options = {
|
|
40908
41000
|
values,
|
|
40909
41001
|
maxRetries: 3
|
|
40910
41002
|
};
|
|
40911
|
-
const model =
|
|
41003
|
+
const model = embedder;
|
|
40912
41004
|
let promise;
|
|
40913
41005
|
switch (model.specificationVersion) {
|
|
40914
41006
|
case "v4":
|
|
40915
41007
|
promise = embedMany({
|
|
40916
41008
|
...options,
|
|
40917
|
-
...
|
|
41009
|
+
...embedderOptions,
|
|
40918
41010
|
model
|
|
40919
41011
|
});
|
|
40920
41012
|
break;
|
|
40921
41013
|
case "v3":
|
|
40922
41014
|
promise = embedMany$1({
|
|
40923
41015
|
...options,
|
|
40924
|
-
...
|
|
41016
|
+
...embedderOptions,
|
|
40925
41017
|
model
|
|
40926
41018
|
});
|
|
40927
41019
|
break;
|
|
40928
41020
|
case "v2":
|
|
40929
41021
|
promise = embedMany$2({
|
|
40930
41022
|
...options,
|
|
40931
|
-
...
|
|
41023
|
+
...embedderOptions,
|
|
40932
41024
|
model
|
|
40933
41025
|
});
|
|
40934
41026
|
break;
|
|
40935
41027
|
default: promise = embedMany$3({
|
|
40936
41028
|
...options,
|
|
40937
|
-
...
|
|
41029
|
+
...embedderOptions,
|
|
40938
41030
|
model
|
|
40939
41031
|
});
|
|
40940
41032
|
}
|
|
@@ -40976,7 +41068,7 @@ ${workingMemory}`;
|
|
|
40976
41068
|
if (!this.embedder && !this.isSelfEmbedding) throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
|
|
40977
41069
|
return buildMessageEmbeddingRows({
|
|
40978
41070
|
items,
|
|
40979
|
-
embed: this.isSelfEmbedding ? void 0 : (chunks) => this.
|
|
41071
|
+
embed: this.isSelfEmbedding ? void 0 : (chunks) => this.embedMessageChunks(chunks),
|
|
40980
41072
|
maxChunkChars: resolveMaxChunkChars({
|
|
40981
41073
|
maxChunkChars: this.configuredMaxChunkChars,
|
|
40982
41074
|
embedder: this.embedder
|
|
@@ -41562,6 +41654,7 @@ Notes:
|
|
|
41562
41654
|
});
|
|
41563
41655
|
for (const r of results) {
|
|
41564
41656
|
if (!r.metadata?.thread_id) continue;
|
|
41657
|
+
if (r.metadata.resource_id !== resourceId || filter?.threadId && r.metadata.thread_id !== filter.threadId) continue;
|
|
41565
41658
|
const groupId = typeof r.metadata.group_id === "string" ? r.metadata.group_id : void 0;
|
|
41566
41659
|
if (!groupId) continue;
|
|
41567
41660
|
queryResults.push({
|
|
@@ -42502,4 +42595,4 @@ Notes:
|
|
|
42502
42595
|
};
|
|
42503
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 };
|
|
42504
42597
|
|
|
42505
|
-
//# sourceMappingURL=src-
|
|
42598
|
+
//# sourceMappingURL=src-Xhctgeae.js.map
|