@mastra/memory 1.41.1-alpha.0 → 1.41.1-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 -3
- package/dist/docs/assets/SOURCE_MAP.json +88 -88
- package/dist/docs/references/docs-harness-background-tasks.md +2 -1
- package/dist/docs/references/docs-memory-semantic-recall.md +24 -1
- package/dist/docs/references/integrations-channels-github.md +63 -24
- package/dist/docs/references/integrations-databases-postgresql.md +46 -0
- package/dist/docs/references/reference-memory-memory-class.md +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +26 -8
- 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/extractor.d.ts +13 -1
- package/dist/processors/observational-memory/extractor.d.ts.map +1 -1
- package/dist/processors/observational-memory/observer-runner.d.ts.map +1 -1
- package/dist/processors/observational-memory/processor.d.ts.map +1 -1
- package/dist/processors/observational-memory/working-memory-extractor.d.ts.map +1 -1
- package/dist/{src-BbbBzTaj.cjs → src-DrWCcSnW.cjs} +170 -293
- package/dist/src-DrWCcSnW.cjs.map +1 -0
- package/dist/{src-BIae5T_v.js → src-wMl-5Ms8.js} +171 -294
- package/dist/{src-BIae5T_v.js.map → src-wMl-5Ms8.js.map} +1 -1
- package/package.json +3 -3
- package/dist/docs/references/reference-migrations-agentnetwork.md +0 -102
- package/dist/docs/references/reference-migrations-upgrade-to-v1-memory.md +0 -290
- package/dist/src-BbbBzTaj.cjs.map +0 -1
|
@@ -23899,6 +23899,9 @@ Observation groups with range IDs and your recall tool allows you to think back
|
|
|
23899
23899
|
${custom}`;
|
|
23900
23900
|
}
|
|
23901
23901
|
// src/processors/observational-memory/extractor.ts
|
|
23902
|
+
/** Sentinel a required inline section uses to signal that no update is needed. */
|
|
23903
|
+
const UNCHANGED_EXTRACTOR_VALUE = "UNCHANGED";
|
|
23904
|
+
const UNCHANGED_PATTERN = new RegExp(`^[\\s\`'"*]*${UNCHANGED_EXTRACTOR_VALUE}[\\s\`'"*.!]*$`, "i");
|
|
23902
23905
|
const BUILT_IN_SLUGS = /* @__PURE__ */ new Set([
|
|
23903
23906
|
"current-task",
|
|
23904
23907
|
"suggested-response",
|
|
@@ -23964,11 +23967,16 @@ var Extractor = class Extractor {
|
|
|
23964
23967
|
metadataKeyPath;
|
|
23965
23968
|
onExtracted;
|
|
23966
23969
|
retryStructuredExtractionOnEmptyObject;
|
|
23970
|
+
/**
|
|
23971
|
+
* @internal Require this inline section in single-thread observer calls. A missing section is recorded as an
|
|
23972
|
+
* extraction failure, and `UNCHANGED` is skipped rather than stored. Batched multi-thread calls treat it as optional.
|
|
23973
|
+
*/
|
|
23974
|
+
required;
|
|
23967
23975
|
/** @internal */
|
|
23968
23976
|
internal;
|
|
23969
23977
|
instructionsConfig;
|
|
23970
23978
|
schemaConfig;
|
|
23971
|
-
constructor(config, internal = false) {
|
|
23979
|
+
constructor(config, internal = false, required = false) {
|
|
23972
23980
|
const name = config.name.trim();
|
|
23973
23981
|
const instructions = typeof config.instructions === "string" ? config.instructions.trim() : void 0;
|
|
23974
23982
|
const slug = slugifyExtractorName(name);
|
|
@@ -23991,6 +23999,7 @@ var Extractor = class Extractor {
|
|
|
23991
23999
|
this.metadataKeyPath = isHook ? false : config.metadataKeyPath ?? `extracted.${slug}`;
|
|
23992
24000
|
this.onExtracted = config.onExtracted;
|
|
23993
24001
|
this.retryStructuredExtractionOnEmptyObject = config.retryStructuredExtractionOnEmptyObject ?? false;
|
|
24002
|
+
this.required = required;
|
|
23994
24003
|
this.internal = internal;
|
|
23995
24004
|
}
|
|
23996
24005
|
async resolve(context) {
|
|
@@ -24006,7 +24015,7 @@ var Extractor = class Extractor {
|
|
|
24006
24015
|
metadataKeyPath: this.metadataKeyPath,
|
|
24007
24016
|
onExtracted: this.onExtracted,
|
|
24008
24017
|
retryStructuredExtractionOnEmptyObject: this.retryStructuredExtractionOnEmptyObject
|
|
24009
|
-
}, this.internal);
|
|
24018
|
+
}, this.internal, this.required);
|
|
24010
24019
|
}
|
|
24011
24020
|
};
|
|
24012
24021
|
async function resolveExtractors(extractors, context) {
|
|
@@ -24061,6 +24070,7 @@ function parseExtractedValues(output, extractors) {
|
|
|
24061
24070
|
const values = {};
|
|
24062
24071
|
const failures = [];
|
|
24063
24072
|
const inlineExtractors = extractors.filter((extractor) => extractor.mode === "inline");
|
|
24073
|
+
const unchangedSlugs = /* @__PURE__ */ new Set();
|
|
24064
24074
|
const regex = new RegExp(`<${EXTRACTED_VALUES_TAG}>([\\s\\S]*?)<\\/${EXTRACTED_VALUES_TAG}>`, "gi");
|
|
24065
24075
|
const matches = [...output.matchAll(regex)];
|
|
24066
24076
|
for (const match of matches) try {
|
|
@@ -24070,6 +24080,10 @@ function parseExtractedValues(output, extractors) {
|
|
|
24070
24080
|
if (!Object.prototype.hasOwnProperty.call(extractedValues, extractor.slug)) continue;
|
|
24071
24081
|
const rawValue = extractedValues[extractor.slug];
|
|
24072
24082
|
if (rawValue === void 0 || rawValue === null || rawValue === "") continue;
|
|
24083
|
+
if (extractor.required && typeof rawValue === "string" && UNCHANGED_PATTERN.test(rawValue)) {
|
|
24084
|
+
unchangedSlugs.add(extractor.slug);
|
|
24085
|
+
continue;
|
|
24086
|
+
}
|
|
24073
24087
|
const parsed = extractor.schema.safeParse(rawValue);
|
|
24074
24088
|
if (parsed.success) values[extractor.slug] = parsed.data;
|
|
24075
24089
|
else failures.push({
|
|
@@ -24084,10 +24098,17 @@ function parseExtractedValues(output, extractors) {
|
|
|
24084
24098
|
});
|
|
24085
24099
|
}
|
|
24086
24100
|
for (const extractor of inlineExtractors) {
|
|
24087
|
-
if (Object.prototype.hasOwnProperty.call(values, extractor.slug)) continue;
|
|
24101
|
+
if (Object.prototype.hasOwnProperty.call(values, extractor.slug) || unchangedSlugs.has(extractor.slug)) continue;
|
|
24088
24102
|
const tagRegex = new RegExp(`<${extractor.slug}>([\\s\\S]*?)<\\/${extractor.slug}>`, "gi");
|
|
24089
24103
|
const rawValue = [...output.matchAll(tagRegex)].at(-1)?.[1]?.trim();
|
|
24090
|
-
if (!rawValue)
|
|
24104
|
+
if (!rawValue) {
|
|
24105
|
+
if (extractor.required) failures.push({
|
|
24106
|
+
slug: extractor.slug,
|
|
24107
|
+
error: `Observer output did not include the required <${extractor.slug}> section`
|
|
24108
|
+
});
|
|
24109
|
+
continue;
|
|
24110
|
+
}
|
|
24111
|
+
if (extractor.required && UNCHANGED_PATTERN.test(rawValue)) continue;
|
|
24091
24112
|
try {
|
|
24092
24113
|
values[extractor.slug] = parseExtractorValue(extractor, rawValue);
|
|
24093
24114
|
} catch (error) {
|
|
@@ -24108,13 +24129,21 @@ function stripExtractorSections(output, extractors) {
|
|
|
24108
24129
|
for (const extractor of inlineExtractors) stripped = stripped.replace(new RegExp(`[ \\t]*<${extractor.slug}>[\\s\\S]*?<\\/${extractor.slug}>\\s*`, "gi"), "");
|
|
24109
24130
|
return stripped;
|
|
24110
24131
|
}
|
|
24132
|
+
/**
|
|
24133
|
+
* Batched multi-thread observer calls share one output across threads, so a per-thread required
|
|
24134
|
+
* section would duplicate resource-level values and record spurious failures. Treat them as optional there.
|
|
24135
|
+
*/
|
|
24136
|
+
function withoutRequiredSections(extractors) {
|
|
24137
|
+
return extractors.map((extractor) => extractor.required ? Object.assign(Object.create(Object.getPrototypeOf(extractor)), extractor, { required: false }) : extractor);
|
|
24138
|
+
}
|
|
24111
24139
|
function buildExtractorOutputSections(extractors) {
|
|
24112
24140
|
const inlineExtractors = extractors.filter((extractor) => extractor.mode === "inline");
|
|
24113
24141
|
if (inlineExtractors.length === 0) return "";
|
|
24114
|
-
|
|
24142
|
+
const sections = inlineExtractors.map((extractor) => `<${extractor.slug}>
|
|
24115
24143
|
${extractor.instructions}
|
|
24116
|
-
Include this section when the observations contain relevant information for <${extractor.slug}>. Write only that information inside the tag
|
|
24117
|
-
</${extractor.slug}>`).join("\n\n")
|
|
24144
|
+
${extractor.required ? `This section is REQUIRED: always output <${extractor.slug}>. If nothing needs to change, write exactly ${UNCHANGED_EXTRACTOR_VALUE} inside the tag.` : `Include this section when the observations contain relevant information for <${extractor.slug}>. Write only that information inside the tag.`}
|
|
24145
|
+
</${extractor.slug}>`).join("\n\n");
|
|
24146
|
+
return `${inlineExtractors.some((extractor) => extractor.required) ? "Additional XML sections:\nOutput these tags after <observations>, following the instructions in each tag." : "Additional optional XML sections:\nIf the observations include information relevant to any of these tags, output that tag after <observations> and include the relevant information."}\n${sections}`;
|
|
24118
24147
|
}
|
|
24119
24148
|
function renderPriorValue(value) {
|
|
24120
24149
|
return typeof value === "string" ? value : JSON.stringify(value);
|
|
@@ -27651,6 +27680,11 @@ var ObserverRunner = class {
|
|
|
27651
27680
|
});
|
|
27652
27681
|
const extractedValues = mergeExtractedValues(parsed.extractedValues, structuredExtraction.values);
|
|
27653
27682
|
const extractionFailures = mergeExtractionFailures(parsed.extractionFailures, structuredExtraction.failures);
|
|
27683
|
+
const failedSlugs = activeExtractors.filter((extractor) => extractor.mode === "inline" && extractor.required).map((extractor) => extractor.slug).filter((slug) => parsed.extractionFailures?.some((failure) => failure.slug === slug));
|
|
27684
|
+
if (failedSlugs.length > 0) this.mastra?.getLogger?.().warn("OM observer could not extract required sections", {
|
|
27685
|
+
failedSlugs,
|
|
27686
|
+
threadId: messagesToObserve[0]?.threadId
|
|
27687
|
+
});
|
|
27654
27688
|
const builtIns = getBuiltInExtractedValues(extractedValues);
|
|
27655
27689
|
const systemPrompt = buildObserverSystemPrompt(false, this.observationConfig.instruction, this.observationConfig.threadTitle, activeExtractors);
|
|
27656
27690
|
this.lastExchange = {
|
|
@@ -27783,10 +27817,11 @@ var ObserverRunner = class {
|
|
|
27783
27817
|
usage: totalUsage
|
|
27784
27818
|
};
|
|
27785
27819
|
}
|
|
27786
|
-
const
|
|
27820
|
+
const batchExtractors = withoutRequiredSections(activeExtractors);
|
|
27821
|
+
const agent = this.createAgent(resolvedModel.model, true, void 0, batchExtractors);
|
|
27787
27822
|
const internalRequestContext = withOmInternalThreadId(requestContext, agent.id);
|
|
27788
27823
|
const multiThreadAttachmentFilter = this.resolveAttachmentFilter(resolvedModel.model, requestContext);
|
|
27789
|
-
const observerMessages = [buildMultiThreadObserverRequestMessage(existingObservations, messagesByThread, threadOrder, priorMetadataByThread, wasTruncated, this.observationConfig.threadTitle,
|
|
27824
|
+
const observerMessages = [buildMultiThreadObserverRequestMessage(existingObservations, messagesByThread, threadOrder, priorMetadataByThread, wasTruncated, this.observationConfig.threadTitle, batchExtractors, {
|
|
27790
27825
|
attachmentFilter: multiThreadAttachmentFilter,
|
|
27791
27826
|
timeZone
|
|
27792
27827
|
})];
|
|
@@ -27842,12 +27877,12 @@ var ObserverRunner = class {
|
|
|
27842
27877
|
});
|
|
27843
27878
|
};
|
|
27844
27879
|
let result = await doGenerate();
|
|
27845
|
-
let parsed = parseMultiThreadObserverOutput(result.text,
|
|
27880
|
+
let parsed = parseMultiThreadObserverOutput(result.text, batchExtractors);
|
|
27846
27881
|
let retriedDueToDegenerate = false;
|
|
27847
27882
|
if (parsed.degenerate) {
|
|
27848
27883
|
omDebug(`[OM:callMultiThreadObserver] degenerate repetition detected, retrying once. ${describeDegenerateOutput(result.text, 2e3)}`);
|
|
27849
27884
|
result = await doGenerate();
|
|
27850
|
-
parsed = parseMultiThreadObserverOutput(result.text,
|
|
27885
|
+
parsed = parseMultiThreadObserverOutput(result.text, batchExtractors);
|
|
27851
27886
|
retriedDueToDegenerate = true;
|
|
27852
27887
|
if (parsed.degenerate) {
|
|
27853
27888
|
omDebug(`[OM:callMultiThreadObserver] degenerate repetition on retry, failing. ${describeDegenerateOutput(result.text, 2e3)}`);
|
|
@@ -27858,7 +27893,7 @@ var ObserverRunner = class {
|
|
|
27858
27893
|
const aggregatedExtractedValues = mergeExtractedValues(...Array.from(parsed.threads, ([threadId, threadResult]) => mergeExtractedValues(threadResult.extractedValues, structuredExtractionByThread.get(threadId)?.values)));
|
|
27859
27894
|
const aggregatedExtractionFailures = mergeExtractionFailures(...Array.from(parsed.threads, ([threadId, threadResult]) => mergeExtractionFailures(threadResult.extractionFailures, structuredExtractionByThread.get(threadId)?.failures)));
|
|
27860
27895
|
const aggregatedBuiltIns = getBuiltInExtractedValues(aggregatedExtractedValues);
|
|
27861
|
-
const systemPrompt = buildObserverSystemPrompt(true, this.observationConfig.instruction, this.observationConfig.threadTitle,
|
|
27896
|
+
const systemPrompt = buildObserverSystemPrompt(true, this.observationConfig.instruction, this.observationConfig.threadTitle, batchExtractors);
|
|
27862
27897
|
this.lastExchange = {
|
|
27863
27898
|
systemPrompt,
|
|
27864
27899
|
observerMessages,
|
|
@@ -27890,7 +27925,7 @@ var ObserverRunner = class {
|
|
|
27890
27925
|
threadTitle: builtIns.threadTitle ?? threadResult.threadTitle,
|
|
27891
27926
|
extractedValues,
|
|
27892
27927
|
extractionFailures,
|
|
27893
|
-
extractors:
|
|
27928
|
+
extractors: batchExtractors
|
|
27894
27929
|
});
|
|
27895
27930
|
}
|
|
27896
27931
|
for (const threadId of results.keys()) for (const msg of messagesByThread.get(threadId) ?? []) this.observedMessageIds.add(msg.id);
|
|
@@ -27929,7 +27964,8 @@ function assertRecognizedObserverOutput(output, label, isRecognized) {
|
|
|
27929
27964
|
function hasSingleThreadObserverContent(text, extractors) {
|
|
27930
27965
|
if (/^[ \t]*<observations>/im.test(text)) return true;
|
|
27931
27966
|
const parsed = parseObserverOutput(text, extractors);
|
|
27932
|
-
|
|
27967
|
+
const requiredSlugs = new Set(extractors.filter((extractor) => extractor.mode === "inline" && extractor.required).map((extractor) => extractor.slug));
|
|
27968
|
+
return Boolean(parsed.degenerate || parsed.observations || parsed.currentTask || parsed.suggestedContinuation || parsed.threadTitle || Object.keys(parsed.extractedValues ?? {}).length || parsed.extractionFailures?.some((failure) => !requiredSlugs.has(failure.slug)));
|
|
27933
27969
|
}
|
|
27934
27970
|
/**
|
|
27935
27971
|
* Multi-thread replies carry every recognised section inside `<thread>` blocks, so a reply
|
|
@@ -29832,7 +29868,7 @@ var WorkingMemoryExtractor = class extends Extractor {
|
|
|
29832
29868
|
});
|
|
29833
29869
|
return document;
|
|
29834
29870
|
}
|
|
29835
|
-
});
|
|
29871
|
+
}, false, true);
|
|
29836
29872
|
}
|
|
29837
29873
|
};
|
|
29838
29874
|
// src/removed-subconscious.ts
|
|
@@ -39859,7 +39895,8 @@ var ObservationalMemoryProcessor = class {
|
|
|
39859
39895
|
ctx = await step.prepare();
|
|
39860
39896
|
} catch (error) {
|
|
39861
39897
|
const err = error instanceof Error ? error : new Error(String(error));
|
|
39862
|
-
const
|
|
39898
|
+
const abortReason = abortSignal?.reason;
|
|
39899
|
+
const abortMessage = abortSignal?.aborted ? abortReason instanceof Error && abortReason.name !== "AbortError" ? `Agent execution was aborted: ${abortReason.message}` : "Agent execution was aborted" : `Encountered error during memory observation: ${err.message}`;
|
|
39863
39900
|
const failedTurn = this.turn;
|
|
39864
39901
|
await failedTurn.end().catch(() => {});
|
|
39865
39902
|
if (this.turn === failedTurn) this.turn = void 0;
|
|
@@ -40168,7 +40205,6 @@ function normalizeObservationalMemoryConfig(config) {
|
|
|
40168
40205
|
function hasWorkingMemoryExtractor(extractors) {
|
|
40169
40206
|
return !!extractors?.some((extractor) => extractor.slug === "working-memory");
|
|
40170
40207
|
}
|
|
40171
|
-
const CHARS_PER_TOKEN = 4;
|
|
40172
40208
|
const DEFAULT_MESSAGE_RANGE = {
|
|
40173
40209
|
before: 1,
|
|
40174
40210
|
after: 1
|
|
@@ -40311,6 +40347,7 @@ var Memory = class Memory extends _mastra_core_memory.MastraMemory {
|
|
|
40311
40347
|
});
|
|
40312
40348
|
this.assertWorkingMemoryStateSignalsCompatibility(mergedConfig);
|
|
40313
40349
|
this.threadConfig = mergedConfig;
|
|
40350
|
+
(0, _mastra_core_memory.resolveMaxChunkChars)({ maxChunkChars: this.configuredMaxChunkChars });
|
|
40314
40351
|
const omConfig = normalizeObservationalMemoryConfig(mergedConfig.observationalMemory);
|
|
40315
40352
|
if (omConfig?.retrieval && typeof omConfig.retrieval === "object" && omConfig.retrieval.vector) {
|
|
40316
40353
|
if (!this.vector) throw new Error("`retrieval: { vector: true }` requires a vector store. Pass a `vector` option to your Memory instance.");
|
|
@@ -40743,7 +40780,7 @@ var Memory = class Memory extends _mastra_core_memory.MastraMemory {
|
|
|
40743
40780
|
const config = this.getMergedThreadConfig(memoryConfig || {});
|
|
40744
40781
|
this.assertWorkingMemoryStateSignalsCompatibility(config);
|
|
40745
40782
|
if (!config.workingMemory?.enabled) throw new Error("Working memory is not enabled for this memory instance");
|
|
40746
|
-
const mutexKey =
|
|
40783
|
+
const mutexKey = (config.workingMemory.scope || "resource") === "resource" ? `resource-${resourceId}` : `thread-${threadId}`;
|
|
40747
40784
|
const mutex = this.updateWorkingMemoryMutexes.has(mutexKey) ? this.updateWorkingMemoryMutexes.get(mutexKey) : new async_mutex.Mutex();
|
|
40748
40785
|
this.updateWorkingMemoryMutexes.set(mutexKey, mutex);
|
|
40749
40786
|
const release = await mutex.acquire();
|
|
@@ -40826,28 +40863,9 @@ ${workingMemory}`;
|
|
|
40826
40863
|
release();
|
|
40827
40864
|
}
|
|
40828
40865
|
}
|
|
40866
|
+
/** Splits text into chunks of at most `tokenSize` English tokens, measured as characters. */
|
|
40829
40867
|
chunkText(text, tokenSize = 4096) {
|
|
40830
|
-
|
|
40831
|
-
const chunks = [];
|
|
40832
|
-
let currentChunk = "";
|
|
40833
|
-
const words = text.split(/\s+/);
|
|
40834
|
-
for (const word of words) {
|
|
40835
|
-
if (word.length > charSize) {
|
|
40836
|
-
if (currentChunk) {
|
|
40837
|
-
chunks.push(currentChunk);
|
|
40838
|
-
currentChunk = "";
|
|
40839
|
-
}
|
|
40840
|
-
for (let i = 0; i < word.length; i += charSize) chunks.push(word.slice(i, i + charSize));
|
|
40841
|
-
continue;
|
|
40842
|
-
}
|
|
40843
|
-
const wordWithSpace = currentChunk ? " " + word : word;
|
|
40844
|
-
if (currentChunk.length + wordWithSpace.length > charSize) {
|
|
40845
|
-
if (currentChunk) chunks.push(currentChunk);
|
|
40846
|
-
currentChunk = word;
|
|
40847
|
-
} else currentChunk += wordWithSpace;
|
|
40848
|
-
}
|
|
40849
|
-
if (currentChunk) chunks.push(currentChunk);
|
|
40850
|
-
return chunks;
|
|
40868
|
+
return (0, _mastra_core_memory.chunkMessageText)(text, tokenSize * _mastra_core_memory.MESSAGE_EMBEDDING_CHARS_PER_TOKEN);
|
|
40851
40869
|
}
|
|
40852
40870
|
hasher = (0, xxhash_wasm.default)();
|
|
40853
40871
|
embeddingCache = new lru_cache.LRUCache({ max: DEFAULT_EMBEDDING_CACHE_MAX_SIZE });
|
|
@@ -40863,11 +40881,23 @@ ${workingMemory}`;
|
|
|
40863
40881
|
return cached;
|
|
40864
40882
|
}
|
|
40865
40883
|
const chunks = this.chunkText(content);
|
|
40884
|
+
const { embeddings, usage } = await this.embedValues(chunks);
|
|
40885
|
+
const result = {
|
|
40886
|
+
embeddings,
|
|
40887
|
+
chunks,
|
|
40888
|
+
usage,
|
|
40889
|
+
dimension: embeddings[0]?.length
|
|
40890
|
+
};
|
|
40891
|
+
this.embeddingCache.set(key, result);
|
|
40892
|
+
return result;
|
|
40893
|
+
}
|
|
40894
|
+
/** Sends texts to the embedder through the AI SDK version that matches its spec. */
|
|
40895
|
+
async embedValues(values) {
|
|
40866
40896
|
if (typeof this.embedder === `undefined`) throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
|
|
40867
40897
|
const isFastEmbed = this.embedder.provider === `fastembed`;
|
|
40868
40898
|
if (isFastEmbed && this.firstEmbed instanceof Promise) await this.firstEmbed;
|
|
40869
40899
|
const options = {
|
|
40870
|
-
values
|
|
40900
|
+
values,
|
|
40871
40901
|
maxRetries: 3
|
|
40872
40902
|
};
|
|
40873
40903
|
const model = this.embedder;
|
|
@@ -40902,106 +40932,87 @@ ${workingMemory}`;
|
|
|
40902
40932
|
}
|
|
40903
40933
|
if (isFastEmbed && !this.firstEmbed) this.firstEmbed = promise;
|
|
40904
40934
|
const { embeddings, usage } = await promise;
|
|
40905
|
-
|
|
40935
|
+
return {
|
|
40906
40936
|
embeddings,
|
|
40907
|
-
|
|
40908
|
-
usage,
|
|
40909
|
-
dimension: embeddings[0]?.length
|
|
40937
|
+
usage
|
|
40910
40938
|
};
|
|
40911
|
-
this.embeddingCache.set(key, result);
|
|
40912
|
-
return result;
|
|
40913
40939
|
}
|
|
40914
|
-
|
|
40940
|
+
/**
|
|
40941
|
+
* Metadata of each thread, spread onto that thread's vector rows so `semanticRecall.filter`
|
|
40942
|
+
* can match thread attributes.
|
|
40943
|
+
*/
|
|
40944
|
+
async loadThreadMetadata(threadIds) {
|
|
40945
|
+
const memoryStore = await this.getMemoryStore();
|
|
40946
|
+
const metadataByThread = /* @__PURE__ */ new Map();
|
|
40947
|
+
await Promise.all(threadIds.map(async (threadId) => {
|
|
40948
|
+
try {
|
|
40949
|
+
const thread = await memoryStore.getThreadById({ threadId });
|
|
40950
|
+
if (thread?.metadata) metadataByThread.set(threadId, thread.metadata);
|
|
40951
|
+
} catch (error) {
|
|
40952
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
40953
|
+
throw new Error(`Could not fetch metadata for thread ${threadId} while writing semantic recall embeddings: ${message}`);
|
|
40954
|
+
}
|
|
40955
|
+
}));
|
|
40956
|
+
return metadataByThread;
|
|
40957
|
+
}
|
|
40958
|
+
/**
|
|
40959
|
+
* Embeds messages into vector rows in the shared format, without writing them. Every
|
|
40960
|
+
* message-vector write in this class builds its rows here.
|
|
40961
|
+
*/
|
|
40962
|
+
async buildMessageVectorRows({ items, embeddedMessages }) {
|
|
40963
|
+
if (items.length === 0) return {
|
|
40964
|
+
ids: [],
|
|
40965
|
+
metadata: [],
|
|
40966
|
+
embeddedEntries: []
|
|
40967
|
+
};
|
|
40968
|
+
if (!this.embedder && !this.isSelfEmbedding) throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
|
|
40969
|
+
return (0, _mastra_core_memory.buildMessageEmbeddingRows)({
|
|
40970
|
+
items,
|
|
40971
|
+
embed: this.isSelfEmbedding ? void 0 : (chunks) => this.embedValues(chunks),
|
|
40972
|
+
maxChunkChars: (0, _mastra_core_memory.resolveMaxChunkChars)({
|
|
40973
|
+
maxChunkChars: this.configuredMaxChunkChars,
|
|
40974
|
+
embedder: this.embedder
|
|
40975
|
+
}),
|
|
40976
|
+
loadThreadMetadata: (threadIds) => this.loadThreadMetadata(threadIds),
|
|
40977
|
+
embeddedMessages,
|
|
40978
|
+
indexName: embeddedMessages ? this.getEmbeddingIndexName(this.isSelfEmbedding ? void 0 : await this.getEmbeddingDimension()) : void 0
|
|
40979
|
+
});
|
|
40980
|
+
}
|
|
40981
|
+
/** Writes rows from {@link buildMessageVectorRows} into the message index for `config`. */
|
|
40982
|
+
async writeMessageVectorRows({ rows, config, embeddedMessages }) {
|
|
40983
|
+
if (!this.vector || rows.ids.length === 0) return;
|
|
40984
|
+
const { indexName } = await this.createEmbeddingIndex(rows.dimension, config);
|
|
40985
|
+
await (0, _mastra_core_memory.upsertMessageVectors)(this.vector, indexName, rows, embeddedMessages);
|
|
40986
|
+
}
|
|
40987
|
+
/**
|
|
40988
|
+
* Embeds messages and writes their vector rows.
|
|
40989
|
+
*
|
|
40990
|
+
* @returns Tokens billed by the embedder, if any.
|
|
40991
|
+
*/
|
|
40992
|
+
async writeMessageVectors(args) {
|
|
40993
|
+
if (!this.vector) return void 0;
|
|
40994
|
+
const rows = await this.buildMessageVectorRows(args);
|
|
40995
|
+
await this.writeMessageVectorRows({
|
|
40996
|
+
...args,
|
|
40997
|
+
rows
|
|
40998
|
+
});
|
|
40999
|
+
return rows.usage;
|
|
41000
|
+
}
|
|
41001
|
+
async saveMessages({ messages, memoryConfig, observabilityContext, embeddedMessages }) {
|
|
40915
41002
|
const span = this.createMemorySpan("save", observabilityContext, void 0, { messageCount: messages.length });
|
|
40916
41003
|
try {
|
|
40917
41004
|
const updatedMessages = this.prepareMessagesForPersistence(messages);
|
|
40918
41005
|
const config = this.getMergedThreadConfig(memoryConfig);
|
|
40919
41006
|
const dbMessages = new _mastra_core_agent.MessageList({ generateMessageId: () => this.generateId() }).add(updatedMessages, "memory").get.all.db();
|
|
40920
|
-
const
|
|
40921
|
-
const
|
|
40922
|
-
|
|
40923
|
-
|
|
40924
|
-
|
|
40925
|
-
|
|
40926
|
-
if (message.threadId) {
|
|
40927
|
-
if (!messagesByThread.has(message.threadId)) messagesByThread.set(message.threadId, []);
|
|
40928
|
-
messagesByThread.get(message.threadId).push(message);
|
|
40929
|
-
}
|
|
40930
|
-
});
|
|
40931
|
-
const threadMetadataMap = /* @__PURE__ */ new Map();
|
|
40932
|
-
await Promise.all(Array.from(messagesByThread.keys()).map(async (threadId) => {
|
|
40933
|
-
try {
|
|
40934
|
-
const thread = await memoryStore.getThreadById({ threadId });
|
|
40935
|
-
if (thread?.metadata) threadMetadataMap.set(threadId, thread.metadata);
|
|
40936
|
-
} catch (error) {
|
|
40937
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
40938
|
-
throw new Error(`Could not fetch metadata for thread ${threadId} while saving semantic recall embeddings: ${message}`);
|
|
40939
|
-
}
|
|
40940
|
-
}));
|
|
40941
|
-
const embeddingData = [];
|
|
40942
|
-
let dimension;
|
|
40943
|
-
await Promise.all(updatedMessages.map(async (message) => {
|
|
40944
|
-
let textForEmbedding = null;
|
|
40945
|
-
if (message.content.content && typeof message.content.content === "string" && message.content.content.trim() !== "") textForEmbedding = message.content.content;
|
|
40946
|
-
else if (message.content.parts && message.content.parts.length > 0) {
|
|
40947
|
-
const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim();
|
|
40948
|
-
if (joined) textForEmbedding = joined;
|
|
40949
|
-
}
|
|
40950
|
-
if (!textForEmbedding) return;
|
|
40951
|
-
let embeddings = [];
|
|
40952
|
-
let documents;
|
|
40953
|
-
let chunks;
|
|
40954
|
-
if (this.isSelfEmbedding) {
|
|
40955
|
-
chunks = this.chunkText(textForEmbedding);
|
|
40956
|
-
documents = chunks;
|
|
40957
|
-
} else {
|
|
40958
|
-
const result = await this.embedMessageContent(textForEmbedding);
|
|
40959
|
-
dimension = result.dimension;
|
|
40960
|
-
if (result.usage?.tokens) totalTokens += result.usage.tokens;
|
|
40961
|
-
embeddings = result.embeddings;
|
|
40962
|
-
chunks = result.chunks;
|
|
40963
|
-
}
|
|
40964
|
-
const threadMetadata = message.threadId ? threadMetadataMap.get(message.threadId) || {} : {};
|
|
40965
|
-
embeddingData.push({
|
|
40966
|
-
embeddings,
|
|
40967
|
-
documents,
|
|
40968
|
-
metadata: chunks.map(() => ({
|
|
40969
|
-
...threadMetadata,
|
|
40970
|
-
message_id: message.id,
|
|
40971
|
-
thread_id: message.threadId,
|
|
40972
|
-
resource_id: message.resourceId,
|
|
40973
|
-
role: message.role,
|
|
40974
|
-
content: textForEmbedding,
|
|
40975
|
-
created_at: message.createdAt instanceof Date ? message.createdAt.toISOString() : String(message.createdAt)
|
|
40976
|
-
}))
|
|
40977
|
-
});
|
|
40978
|
-
}));
|
|
40979
|
-
if (embeddingData.length > 0 && (this.isSelfEmbedding || dimension !== void 0)) {
|
|
40980
|
-
if (typeof this.vector === `undefined`) throw new Error(`Tried to upsert embeddings but this Memory instance doesn't have an attached vector db.`);
|
|
40981
|
-
const { indexName } = await this.createEmbeddingIndex(dimension, config);
|
|
40982
|
-
const allVectors = [];
|
|
40983
|
-
const allMetadata = [];
|
|
40984
|
-
const allDocuments = [];
|
|
40985
|
-
for (const data of embeddingData) {
|
|
40986
|
-
allVectors.push(...data.embeddings);
|
|
40987
|
-
if (data.documents) allDocuments.push(...data.documents);
|
|
40988
|
-
allMetadata.push(...data.metadata);
|
|
40989
|
-
}
|
|
40990
|
-
if (this.isSelfEmbedding) await this.vector.upsert({
|
|
40991
|
-
indexName,
|
|
40992
|
-
documents: allDocuments,
|
|
40993
|
-
metadata: allMetadata
|
|
40994
|
-
});
|
|
40995
|
-
else await this.vector.upsert({
|
|
40996
|
-
indexName,
|
|
40997
|
-
vectors: allVectors,
|
|
40998
|
-
metadata: allMetadata
|
|
40999
|
-
});
|
|
41000
|
-
}
|
|
41001
|
-
}
|
|
41007
|
+
const result = await (await this.getMemoryStore()).saveMessages({ messages: dbMessages });
|
|
41008
|
+
const usage = this.vector && config.semanticRecall ? await this.writeMessageVectors({
|
|
41009
|
+
items: updatedMessages.map((message) => ({ message })),
|
|
41010
|
+
config,
|
|
41011
|
+
embeddedMessages
|
|
41012
|
+
}) : void 0;
|
|
41002
41013
|
const saveResult = {
|
|
41003
41014
|
...result,
|
|
41004
|
-
usage
|
|
41015
|
+
usage
|
|
41005
41016
|
};
|
|
41006
41017
|
span?.end({
|
|
41007
41018
|
output: { success: true },
|
|
@@ -41724,51 +41735,6 @@ Notes:
|
|
|
41724
41735
|
return collected;
|
|
41725
41736
|
}
|
|
41726
41737
|
/**
|
|
41727
|
-
* Index a list of messages directly (without querying storage).
|
|
41728
|
-
* Used by observe-time indexing to vectorize newly-observed messages.
|
|
41729
|
-
*/
|
|
41730
|
-
async indexMessagesList(messages) {
|
|
41731
|
-
if (!this.vector || !this.embedder) return;
|
|
41732
|
-
const embeddingData = [];
|
|
41733
|
-
let dimension;
|
|
41734
|
-
await Promise.all(messages.map(async (message) => {
|
|
41735
|
-
let textForEmbedding = null;
|
|
41736
|
-
if (message.content.content && typeof message.content.content === "string" && message.content.content.trim() !== "") textForEmbedding = message.content.content;
|
|
41737
|
-
else if (message.content.parts && message.content.parts.length > 0) {
|
|
41738
|
-
const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim();
|
|
41739
|
-
if (joined) textForEmbedding = joined;
|
|
41740
|
-
}
|
|
41741
|
-
if (!textForEmbedding) return;
|
|
41742
|
-
const embedResult = await this.embedMessageContent(textForEmbedding);
|
|
41743
|
-
dimension = embedResult.dimension;
|
|
41744
|
-
embeddingData.push({
|
|
41745
|
-
embeddings: embedResult.embeddings,
|
|
41746
|
-
metadata: embedResult.chunks.map(() => ({
|
|
41747
|
-
message_id: message.id,
|
|
41748
|
-
thread_id: message.threadId,
|
|
41749
|
-
resource_id: message.resourceId,
|
|
41750
|
-
role: message.role,
|
|
41751
|
-
content: textForEmbedding,
|
|
41752
|
-
created_at: message.createdAt instanceof Date ? message.createdAt.toISOString() : String(message.createdAt)
|
|
41753
|
-
}))
|
|
41754
|
-
});
|
|
41755
|
-
}));
|
|
41756
|
-
if (embeddingData.length > 0 && dimension !== void 0) {
|
|
41757
|
-
const { indexName } = await this.createEmbeddingIndex(dimension);
|
|
41758
|
-
const allVectors = [];
|
|
41759
|
-
const allMetadata = [];
|
|
41760
|
-
for (const data of embeddingData) {
|
|
41761
|
-
allVectors.push(...data.embeddings);
|
|
41762
|
-
allMetadata.push(...data.metadata);
|
|
41763
|
-
}
|
|
41764
|
-
await this.vector.upsert({
|
|
41765
|
-
indexName,
|
|
41766
|
-
vectors: allVectors,
|
|
41767
|
-
metadata: allMetadata
|
|
41768
|
-
});
|
|
41769
|
-
}
|
|
41770
|
-
}
|
|
41771
|
-
/**
|
|
41772
41738
|
* Check whether retrieval search (vector-based) is enabled.
|
|
41773
41739
|
* Returns true when `retrieval: { vector: true }` and Memory has a vector store plus either an
|
|
41774
41740
|
* embedder or a store that generates embeddings itself.
|
|
@@ -41874,43 +41840,19 @@ Notes:
|
|
|
41874
41840
|
const messagesWithTextUpdates = [...textForEmbeddingById.keys()].map((id) => ({ id }));
|
|
41875
41841
|
if (messagesWithTextUpdates.length > 0) {
|
|
41876
41842
|
const existingMessagesMap = new Map(existing.messages.map((m) => [m.id, m]));
|
|
41877
|
-
const
|
|
41878
|
-
|
|
41879
|
-
const
|
|
41880
|
-
|
|
41881
|
-
|
|
41882
|
-
|
|
41883
|
-
|
|
41884
|
-
|
|
41885
|
-
|
|
41886
|
-
|
|
41887
|
-
|
|
41888
|
-
|
|
41889
|
-
|
|
41890
|
-
chunks = this.chunkText(textForEmbedding);
|
|
41891
|
-
documents = chunks;
|
|
41892
|
-
} else {
|
|
41893
|
-
const result = await this.embedMessageContent(textForEmbedding);
|
|
41894
|
-
dimension = result.dimension;
|
|
41895
|
-
embeddings = result.embeddings;
|
|
41896
|
-
chunks = result.chunks;
|
|
41897
|
-
}
|
|
41898
|
-
embeddingData.push({
|
|
41899
|
-
embeddings,
|
|
41900
|
-
documents,
|
|
41901
|
-
metadata: chunks.map(() => ({
|
|
41902
|
-
message_id: message.id,
|
|
41903
|
-
thread_id: existingMessage.threadId,
|
|
41904
|
-
resource_id: existingMessage.resourceId,
|
|
41905
|
-
role: existingMessage.role,
|
|
41906
|
-
content: textForEmbedding,
|
|
41907
|
-
created_at: existingMessage.createdAt instanceof Date ? existingMessage.createdAt.toISOString() : String(existingMessage.createdAt)
|
|
41908
|
-
}))
|
|
41909
|
-
});
|
|
41910
|
-
messageIdsWithNewEmbeddings.add(message.id);
|
|
41911
|
-
} else messageIdsWithClearedContent.add(message.id);
|
|
41912
|
-
}));
|
|
41913
|
-
const messageIdsNeedingDeletion = /* @__PURE__ */ new Set([...messageIdsWithClearedContent, ...messageIdsWithNewEmbeddings]);
|
|
41843
|
+
const messageIdsNeedingDeletion = /* @__PURE__ */ new Set();
|
|
41844
|
+
const items = [];
|
|
41845
|
+
for (const { id } of messagesWithTextUpdates) {
|
|
41846
|
+
const existingMessage = existingMessagesMap.get(id);
|
|
41847
|
+
if (!existingMessage) continue;
|
|
41848
|
+
messageIdsNeedingDeletion.add(id);
|
|
41849
|
+
const text = textForEmbeddingById.get(id);
|
|
41850
|
+
if (text) items.push({
|
|
41851
|
+
message: existingMessage,
|
|
41852
|
+
text
|
|
41853
|
+
});
|
|
41854
|
+
}
|
|
41855
|
+
const rows = await this.buildMessageVectorRows({ items });
|
|
41914
41856
|
if (messageIdsNeedingDeletion.size > 0) try {
|
|
41915
41857
|
const memoryIndexes = await this.getMemoryVectorIndexes([this.messageIndexPrefix]);
|
|
41916
41858
|
const idsToDelete = [...messageIdsNeedingDeletion];
|
|
@@ -41933,27 +41875,10 @@ Notes:
|
|
|
41933
41875
|
} catch {
|
|
41934
41876
|
this.logger.debug("Failed to clean up old vectors during message update");
|
|
41935
41877
|
}
|
|
41936
|
-
|
|
41937
|
-
|
|
41938
|
-
|
|
41939
|
-
|
|
41940
|
-
const allDocuments = [];
|
|
41941
|
-
for (const data of embeddingData) {
|
|
41942
|
-
allVectors.push(...data.embeddings);
|
|
41943
|
-
if (data.documents) allDocuments.push(...data.documents);
|
|
41944
|
-
allMetadata.push(...data.metadata);
|
|
41945
|
-
}
|
|
41946
|
-
if (this.isSelfEmbedding) await this.vector.upsert({
|
|
41947
|
-
indexName,
|
|
41948
|
-
documents: allDocuments,
|
|
41949
|
-
metadata: allMetadata
|
|
41950
|
-
});
|
|
41951
|
-
else await this.vector.upsert({
|
|
41952
|
-
indexName,
|
|
41953
|
-
vectors: allVectors,
|
|
41954
|
-
metadata: allMetadata
|
|
41955
|
-
});
|
|
41956
|
-
}
|
|
41878
|
+
await this.writeMessageVectorRows({
|
|
41879
|
+
rows,
|
|
41880
|
+
config
|
|
41881
|
+
});
|
|
41957
41882
|
}
|
|
41958
41883
|
}
|
|
41959
41884
|
return memoryStore.updateMessages({ messages });
|
|
@@ -42218,6 +42143,7 @@ Notes:
|
|
|
42218
42143
|
threadId,
|
|
42219
42144
|
perPage: false
|
|
42220
42145
|
});
|
|
42146
|
+
const rows = await this.buildMessageVectorRows({ items: messages.map((message) => ({ message })) });
|
|
42221
42147
|
const messageIndexes = await this.getMemoryVectorIndexes([this.messageIndexPrefix]);
|
|
42222
42148
|
await Promise.all(messageIndexes.map(async (indexName) => {
|
|
42223
42149
|
await this.vector.deleteVectors({
|
|
@@ -42225,7 +42151,10 @@ Notes:
|
|
|
42225
42151
|
filter: { thread_id: threadId }
|
|
42226
42152
|
});
|
|
42227
42153
|
}));
|
|
42228
|
-
|
|
42154
|
+
await this.writeMessageVectorRows({
|
|
42155
|
+
rows,
|
|
42156
|
+
config
|
|
42157
|
+
});
|
|
42229
42158
|
} catch (error) {
|
|
42230
42159
|
this.logger.error("Failed to migrate semantic-recall vectors during thread transfer", {
|
|
42231
42160
|
threadId,
|
|
@@ -42373,67 +42302,15 @@ Notes:
|
|
|
42373
42302
|
return cloned;
|
|
42374
42303
|
}
|
|
42375
42304
|
/**
|
|
42376
|
-
* Embed cloned messages for semantic recall.
|
|
42377
|
-
*
|
|
42305
|
+
* Embed cloned messages for semantic recall. Cloned messages have new ids, so they get rows of
|
|
42306
|
+
* their own next to the source thread's rows.
|
|
42378
42307
|
*/
|
|
42379
42308
|
async embedClonedMessages(messages, config) {
|
|
42380
42309
|
if (!this.vector || !this.embedder && !this.isSelfEmbedding) return;
|
|
42381
|
-
|
|
42382
|
-
|
|
42383
|
-
|
|
42384
|
-
|
|
42385
|
-
if (message.content?.content && typeof message.content.content === "string" && message.content.content.trim() !== "") textForEmbedding = message.content.content;
|
|
42386
|
-
else if (message.content?.parts && message.content.parts.length > 0) {
|
|
42387
|
-
const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim();
|
|
42388
|
-
if (joined) textForEmbedding = joined;
|
|
42389
|
-
}
|
|
42390
|
-
if (!textForEmbedding) return;
|
|
42391
|
-
let embeddings = [];
|
|
42392
|
-
let documents;
|
|
42393
|
-
let chunks;
|
|
42394
|
-
if (this.isSelfEmbedding) {
|
|
42395
|
-
chunks = this.chunkText(textForEmbedding);
|
|
42396
|
-
documents = chunks;
|
|
42397
|
-
} else {
|
|
42398
|
-
const result = await this.embedMessageContent(textForEmbedding);
|
|
42399
|
-
dimension = result.dimension;
|
|
42400
|
-
embeddings = result.embeddings;
|
|
42401
|
-
chunks = result.chunks;
|
|
42402
|
-
}
|
|
42403
|
-
embeddingData.push({
|
|
42404
|
-
embeddings,
|
|
42405
|
-
documents,
|
|
42406
|
-
metadata: chunks.map(() => ({
|
|
42407
|
-
message_id: message.id,
|
|
42408
|
-
thread_id: message.threadId,
|
|
42409
|
-
resource_id: message.resourceId,
|
|
42410
|
-
role: message.role,
|
|
42411
|
-
content: textForEmbedding,
|
|
42412
|
-
created_at: message.createdAt instanceof Date ? message.createdAt.toISOString() : String(message.createdAt)
|
|
42413
|
-
}))
|
|
42414
|
-
});
|
|
42415
|
-
}));
|
|
42416
|
-
if (embeddingData.length > 0 && (this.isSelfEmbedding || dimension !== void 0)) {
|
|
42417
|
-
const { indexName } = await this.createEmbeddingIndex(dimension, config);
|
|
42418
|
-
const allVectors = [];
|
|
42419
|
-
const allMetadata = [];
|
|
42420
|
-
const allDocuments = [];
|
|
42421
|
-
for (const data of embeddingData) {
|
|
42422
|
-
allVectors.push(...data.embeddings);
|
|
42423
|
-
if (data.documents) allDocuments.push(...data.documents);
|
|
42424
|
-
allMetadata.push(...data.metadata);
|
|
42425
|
-
}
|
|
42426
|
-
if (this.isSelfEmbedding) await this.vector.upsert({
|
|
42427
|
-
indexName,
|
|
42428
|
-
documents: allDocuments,
|
|
42429
|
-
metadata: allMetadata
|
|
42430
|
-
});
|
|
42431
|
-
else await this.vector.upsert({
|
|
42432
|
-
indexName,
|
|
42433
|
-
vectors: allVectors,
|
|
42434
|
-
metadata: allMetadata
|
|
42435
|
-
});
|
|
42436
|
-
}
|
|
42310
|
+
await this.writeMessageVectors({
|
|
42311
|
+
items: messages.map((message) => ({ message })),
|
|
42312
|
+
config
|
|
42313
|
+
});
|
|
42437
42314
|
}
|
|
42438
42315
|
/**
|
|
42439
42316
|
* Get the clone metadata from a thread if it was cloned from another thread.
|
|
@@ -42892,4 +42769,4 @@ Object.defineProperty(exports, "wrapInObservationGroup", {
|
|
|
42892
42769
|
}
|
|
42893
42770
|
});
|
|
42894
42771
|
|
|
42895
|
-
//# sourceMappingURL=src-
|
|
42772
|
+
//# sourceMappingURL=src-DrWCcSnW.cjs.map
|