@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
|
@@ -28100,6 +28100,19 @@ function buildEstimateKey(kind, text) {
|
|
|
28100
28100
|
function resolveEstimatorId() {
|
|
28101
28101
|
return "tokenx";
|
|
28102
28102
|
}
|
|
28103
|
+
const ATTACHMENT_CONTENT_PART_TYPES = /* @__PURE__ */ new Set([
|
|
28104
|
+
"image",
|
|
28105
|
+
"image-data",
|
|
28106
|
+
"media",
|
|
28107
|
+
"audio",
|
|
28108
|
+
"file-data"
|
|
28109
|
+
]);
|
|
28110
|
+
/** Mirrors the parts countMultimodalToolResultContent counts as attachments. */
|
|
28111
|
+
function isAttachmentContentPart(item) {
|
|
28112
|
+
if (!item || typeof item !== "object") return false;
|
|
28113
|
+
const contentPart = item;
|
|
28114
|
+
return ATTACHMENT_CONTENT_PART_TYPES.has(contentPart.type) && typeof contentPart.data === "string";
|
|
28115
|
+
}
|
|
28103
28116
|
function isTokenEstimateEntry(value) {
|
|
28104
28117
|
if (!value || typeof value !== "object") return false;
|
|
28105
28118
|
const entry = value;
|
|
@@ -28892,12 +28905,12 @@ var TokenCounter = class TokenCounter {
|
|
|
28892
28905
|
}
|
|
28893
28906
|
countMultimodalToolResultContent(part, toolResult) {
|
|
28894
28907
|
if (!toolResult || typeof toolResult !== "object") return;
|
|
28908
|
+
const output = toolResult;
|
|
28909
|
+
const content = output.type === "content" && Array.isArray(output.value) ? output.value : output.content;
|
|
28910
|
+
if (!Array.isArray(content) || !content.some(isAttachmentContentPart)) return;
|
|
28895
28911
|
const resultKey = buildEstimateKey("tool-result-multimodal-content-source", JSON.stringify(toolResult));
|
|
28896
28912
|
const cached = this.multimodalToolResultCounts.get(part);
|
|
28897
28913
|
if (cached?.resultKey === resultKey) return cached.tokens;
|
|
28898
|
-
const output = toolResult;
|
|
28899
|
-
const content = output.type === "content" && Array.isArray(output.value) ? output.value : output.content;
|
|
28900
|
-
if (!Array.isArray(content)) return;
|
|
28901
28914
|
let hasAttachment = false;
|
|
28902
28915
|
let tokens = 0;
|
|
28903
28916
|
const cacheParts = [];
|
|
@@ -39712,12 +39725,25 @@ function getOmObservabilityContext(args) {
|
|
|
39712
39725
|
metrics: args.metrics
|
|
39713
39726
|
};
|
|
39714
39727
|
}
|
|
39715
|
-
/** Key used to store gateway
|
|
39716
|
-
const GATEWAY_STATE_KEY = "
|
|
39728
|
+
/** Key used to store whether the gateway manages memory for the current step in per-processor state. */
|
|
39729
|
+
const GATEWAY_STATE_KEY = "__isGatewayMemoryManaged";
|
|
39717
39730
|
/** Step number OM last recovered from a context-overflow error, so each step retries at most once. */
|
|
39718
39731
|
const CONTEXT_OVERFLOW_STEP_KEY = "__omContextOverflowStep";
|
|
39719
|
-
/**
|
|
39720
|
-
|
|
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());
|
|
39721
39747
|
return typeof model === "object" && model !== null && "gatewayId" in model && model.gatewayId === "mastra";
|
|
39722
39748
|
}
|
|
39723
39749
|
function injectObservationContextMessages({ messageList, systemMessages, continuationMessage, hasObservations, threadId, resourceId }) {
|
|
@@ -39783,6 +39809,34 @@ var ObservationalMemoryProcessor = class {
|
|
|
39783
39809
|
this.memory = memory;
|
|
39784
39810
|
this.temporalMarkers = options?.temporalMarkers ?? false;
|
|
39785
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
|
+
}
|
|
39786
39840
|
async processInputStep(args) {
|
|
39787
39841
|
const { messageList, requestContext, stepNumber, state: _state, writer, model, abortSignal, abort, messageId, rotateResponseMessageId } = args;
|
|
39788
39842
|
const state = _state ?? {};
|
|
@@ -39792,9 +39846,11 @@ var ObservationalMemoryProcessor = class {
|
|
|
39792
39846
|
omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null — returning early`);
|
|
39793
39847
|
return messageList;
|
|
39794
39848
|
}
|
|
39795
|
-
|
|
39796
|
-
|
|
39797
|
-
|
|
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`);
|
|
39798
39854
|
return messageList;
|
|
39799
39855
|
}
|
|
39800
39856
|
const { threadId, resourceId } = context;
|
|
@@ -39984,7 +40040,10 @@ var ObservationalMemoryProcessor = class {
|
|
|
39984
40040
|
const state = _state ?? {};
|
|
39985
40041
|
const context = this.engine.getThreadContext(requestContext, messageList);
|
|
39986
40042
|
if (!context) return messageList;
|
|
39987
|
-
if (state[GATEWAY_STATE_KEY])
|
|
40043
|
+
if (state[GATEWAY_STATE_KEY]) {
|
|
40044
|
+
await this.endActiveTurn(state, messageList.cloneForPersistence());
|
|
40045
|
+
return messageList;
|
|
40046
|
+
}
|
|
39988
40047
|
state.__omObservabilityContext = getOmObservabilityContext(args);
|
|
39989
40048
|
return this.engine.getTokenCounter().runWithModelContext(state.__omActorModelContext, async () => {
|
|
39990
40049
|
if ((0, _mastra_core_memory.parseMemoryRequestContext)(requestContext)?.memoryConfig?.readOnly) return messageList;
|
|
@@ -40506,7 +40565,7 @@ var Memory = class Memory extends _mastra_core_memory.MastraMemory {
|
|
|
40506
40565
|
}
|
|
40507
40566
|
}
|
|
40508
40567
|
const threshold = (typeof config.semanticRecall === "object" ? config.semanticRecall : void 0)?.threshold;
|
|
40509
|
-
const filteredVectorResults =
|
|
40568
|
+
const filteredVectorResults = vectorResults.filter((r) => (threshold === void 0 || r.score >= threshold) && (resourceScope ? r.metadata?.resource_id === resourceId : r.metadata?.thread_id === threadId));
|
|
40510
40569
|
const memoryStore = await this.getMemoryStore();
|
|
40511
40570
|
const include = filteredVectorResults.map((r) => ({
|
|
40512
40571
|
id: r.metadata?.message_id,
|
|
@@ -40570,6 +40629,7 @@ var Memory = class Memory extends _mastra_core_memory.MastraMemory {
|
|
|
40570
40629
|
rawMessages = shouldGetNewestAndReverse ? paginatedResult.messages.reverse() : paginatedResult.messages;
|
|
40571
40630
|
({total, page: resultPage, perPage: resultPerPage, hasMore} = paginatedResult);
|
|
40572
40631
|
}
|
|
40632
|
+
if (include.length) rawMessages = rawMessages.filter((message) => message.threadId === threadId || resourceScope && message.resourceId === resourceId);
|
|
40573
40633
|
const messages = filterSystemReminderMessages(new _mastra_core_agent.MessageList({
|
|
40574
40634
|
threadId,
|
|
40575
40635
|
resourceId
|
|
@@ -40920,42 +40980,74 @@ ${workingMemory}`;
|
|
|
40920
40980
|
this.embeddingCache.set(key, result);
|
|
40921
40981
|
return result;
|
|
40922
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
|
+
}
|
|
40923
41015
|
/** Sends texts to the embedder through the AI SDK version that matches its spec. */
|
|
40924
|
-
async embedValues(values) {
|
|
40925
|
-
if (typeof
|
|
40926
|
-
const isFastEmbed =
|
|
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`;
|
|
40927
41019
|
if (isFastEmbed && this.firstEmbed instanceof Promise) await this.firstEmbed;
|
|
40928
41020
|
const options = {
|
|
40929
41021
|
values,
|
|
40930
41022
|
maxRetries: 3
|
|
40931
41023
|
};
|
|
40932
|
-
const model =
|
|
41024
|
+
const model = embedder;
|
|
40933
41025
|
let promise;
|
|
40934
41026
|
switch (model.specificationVersion) {
|
|
40935
41027
|
case "v4":
|
|
40936
41028
|
promise = embedMany({
|
|
40937
41029
|
...options,
|
|
40938
|
-
...
|
|
41030
|
+
...embedderOptions,
|
|
40939
41031
|
model
|
|
40940
41032
|
});
|
|
40941
41033
|
break;
|
|
40942
41034
|
case "v3":
|
|
40943
41035
|
promise = embedMany$1({
|
|
40944
41036
|
...options,
|
|
40945
|
-
...
|
|
41037
|
+
...embedderOptions,
|
|
40946
41038
|
model
|
|
40947
41039
|
});
|
|
40948
41040
|
break;
|
|
40949
41041
|
case "v2":
|
|
40950
41042
|
promise = embedMany$2({
|
|
40951
41043
|
...options,
|
|
40952
|
-
...
|
|
41044
|
+
...embedderOptions,
|
|
40953
41045
|
model
|
|
40954
41046
|
});
|
|
40955
41047
|
break;
|
|
40956
41048
|
default: promise = embedMany$3({
|
|
40957
41049
|
...options,
|
|
40958
|
-
...
|
|
41050
|
+
...embedderOptions,
|
|
40959
41051
|
model
|
|
40960
41052
|
});
|
|
40961
41053
|
}
|
|
@@ -40997,7 +41089,7 @@ ${workingMemory}`;
|
|
|
40997
41089
|
if (!this.embedder && !this.isSelfEmbedding) throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
|
|
40998
41090
|
return (0, _mastra_core_memory.buildMessageEmbeddingRows)({
|
|
40999
41091
|
items,
|
|
41000
|
-
embed: this.isSelfEmbedding ? void 0 : (chunks) => this.
|
|
41092
|
+
embed: this.isSelfEmbedding ? void 0 : (chunks) => this.embedMessageChunks(chunks),
|
|
41001
41093
|
maxChunkChars: (0, _mastra_core_memory.resolveMaxChunkChars)({
|
|
41002
41094
|
maxChunkChars: this.configuredMaxChunkChars,
|
|
41003
41095
|
embedder: this.embedder
|
|
@@ -41583,6 +41675,7 @@ Notes:
|
|
|
41583
41675
|
});
|
|
41584
41676
|
for (const r of results) {
|
|
41585
41677
|
if (!r.metadata?.thread_id) continue;
|
|
41678
|
+
if (r.metadata.resource_id !== resourceId || filter?.threadId && r.metadata.thread_id !== filter.threadId) continue;
|
|
41586
41679
|
const groupId = typeof r.metadata.group_id === "string" ? r.metadata.group_id : void 0;
|
|
41587
41680
|
if (!groupId) continue;
|
|
41588
41681
|
queryResults.push({
|
|
@@ -42798,4 +42891,4 @@ Object.defineProperty(exports, "wrapInObservationGroup", {
|
|
|
42798
42891
|
}
|
|
42799
42892
|
});
|
|
42800
42893
|
|
|
42801
|
-
//# sourceMappingURL=src-
|
|
42894
|
+
//# sourceMappingURL=src-BLniLryu.cjs.map
|