@mastra/memory 1.41.1-alpha.0 → 1.41.1-alpha.1
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 +52 -52
- 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/processor.d.ts.map +1 -1
- package/dist/{src-BIae5T_v.js → src-BL6KZcyR.js} +119 -278
- package/dist/{src-BIae5T_v.js.map → src-BL6KZcyR.js.map} +1 -1
- package/dist/{src-BbbBzTaj.cjs → src-Bo9Kpfk_.cjs} +118 -277
- package/dist/src-Bo9Kpfk_.cjs.map +1 -0
- package/package.json +4 -4
- 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
|
@@ -6,7 +6,7 @@ import { toJSONSchema } from "zod/v4/core";
|
|
|
6
6
|
import { Agent, MessageList } from "@mastra/core/agent";
|
|
7
7
|
import { ErrorCategory, ErrorDomain, MastraError, classifyProviderError } from "@mastra/core/error";
|
|
8
8
|
import { coreFeatures } from "@mastra/core/features";
|
|
9
|
-
import { MastraMemory, getMemoryTokenBoundary, getThreadOMMetadata, isAfterMemoryTokenBoundary, isThreadTitlePinned, loadMessageHistory, normalizeMessageHistoryConfig, parseMemoryRequestContext, setThreadOMMetadata } from "@mastra/core/memory";
|
|
9
|
+
import { MESSAGE_EMBEDDING_CHARS_PER_TOKEN, MastraMemory, buildMessageEmbeddingRows, chunkMessageText, getMemoryTokenBoundary, getThreadOMMetadata, isAfterMemoryTokenBoundary, isThreadTitlePinned, loadMessageHistory, normalizeMessageHistoryConfig, parseMemoryRequestContext, resolveMaxChunkChars, setThreadOMMetadata, upsertMessageVectors } from "@mastra/core/memory";
|
|
10
10
|
import * as coreObservability from "@mastra/core/observability";
|
|
11
11
|
import { EntityType, SpanType, createObservabilityContext, getOrCreateSpan } from "@mastra/core/observability";
|
|
12
12
|
import { MessageHistory, MessageHistory as MessageHistory$1, SemanticRecall, TokenLimiterProcessor, WorkingMemory } from "@mastra/core/processors";
|
|
@@ -39838,7 +39838,8 @@ var ObservationalMemoryProcessor = class {
|
|
|
39838
39838
|
ctx = await step.prepare();
|
|
39839
39839
|
} catch (error) {
|
|
39840
39840
|
const err = error instanceof Error ? error : new Error(String(error));
|
|
39841
|
-
const
|
|
39841
|
+
const abortReason = abortSignal?.reason;
|
|
39842
|
+
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}`;
|
|
39842
39843
|
const failedTurn = this.turn;
|
|
39843
39844
|
await failedTurn.end().catch(() => {});
|
|
39844
39845
|
if (this.turn === failedTurn) this.turn = void 0;
|
|
@@ -40147,7 +40148,6 @@ function normalizeObservationalMemoryConfig(config) {
|
|
|
40147
40148
|
function hasWorkingMemoryExtractor(extractors) {
|
|
40148
40149
|
return !!extractors?.some((extractor) => extractor.slug === "working-memory");
|
|
40149
40150
|
}
|
|
40150
|
-
const CHARS_PER_TOKEN = 4;
|
|
40151
40151
|
const DEFAULT_MESSAGE_RANGE = {
|
|
40152
40152
|
before: 1,
|
|
40153
40153
|
after: 1
|
|
@@ -40290,6 +40290,7 @@ var Memory = class Memory extends MastraMemory {
|
|
|
40290
40290
|
});
|
|
40291
40291
|
this.assertWorkingMemoryStateSignalsCompatibility(mergedConfig);
|
|
40292
40292
|
this.threadConfig = mergedConfig;
|
|
40293
|
+
resolveMaxChunkChars({ maxChunkChars: this.configuredMaxChunkChars });
|
|
40293
40294
|
const omConfig = normalizeObservationalMemoryConfig(mergedConfig.observationalMemory);
|
|
40294
40295
|
if (omConfig?.retrieval && typeof omConfig.retrieval === "object" && omConfig.retrieval.vector) {
|
|
40295
40296
|
if (!this.vector) throw new Error("`retrieval: { vector: true }` requires a vector store. Pass a `vector` option to your Memory instance.");
|
|
@@ -40805,28 +40806,9 @@ ${workingMemory}`;
|
|
|
40805
40806
|
release();
|
|
40806
40807
|
}
|
|
40807
40808
|
}
|
|
40809
|
+
/** Splits text into chunks of at most `tokenSize` English tokens, measured as characters. */
|
|
40808
40810
|
chunkText(text, tokenSize = 4096) {
|
|
40809
|
-
|
|
40810
|
-
const chunks = [];
|
|
40811
|
-
let currentChunk = "";
|
|
40812
|
-
const words = text.split(/\s+/);
|
|
40813
|
-
for (const word of words) {
|
|
40814
|
-
if (word.length > charSize) {
|
|
40815
|
-
if (currentChunk) {
|
|
40816
|
-
chunks.push(currentChunk);
|
|
40817
|
-
currentChunk = "";
|
|
40818
|
-
}
|
|
40819
|
-
for (let i = 0; i < word.length; i += charSize) chunks.push(word.slice(i, i + charSize));
|
|
40820
|
-
continue;
|
|
40821
|
-
}
|
|
40822
|
-
const wordWithSpace = currentChunk ? " " + word : word;
|
|
40823
|
-
if (currentChunk.length + wordWithSpace.length > charSize) {
|
|
40824
|
-
if (currentChunk) chunks.push(currentChunk);
|
|
40825
|
-
currentChunk = word;
|
|
40826
|
-
} else currentChunk += wordWithSpace;
|
|
40827
|
-
}
|
|
40828
|
-
if (currentChunk) chunks.push(currentChunk);
|
|
40829
|
-
return chunks;
|
|
40811
|
+
return chunkMessageText(text, tokenSize * MESSAGE_EMBEDDING_CHARS_PER_TOKEN);
|
|
40830
40812
|
}
|
|
40831
40813
|
hasher = xxhash();
|
|
40832
40814
|
embeddingCache = new LRUCache({ max: DEFAULT_EMBEDDING_CACHE_MAX_SIZE });
|
|
@@ -40842,11 +40824,23 @@ ${workingMemory}`;
|
|
|
40842
40824
|
return cached;
|
|
40843
40825
|
}
|
|
40844
40826
|
const chunks = this.chunkText(content);
|
|
40827
|
+
const { embeddings, usage } = await this.embedValues(chunks);
|
|
40828
|
+
const result = {
|
|
40829
|
+
embeddings,
|
|
40830
|
+
chunks,
|
|
40831
|
+
usage,
|
|
40832
|
+
dimension: embeddings[0]?.length
|
|
40833
|
+
};
|
|
40834
|
+
this.embeddingCache.set(key, result);
|
|
40835
|
+
return result;
|
|
40836
|
+
}
|
|
40837
|
+
/** Sends texts to the embedder through the AI SDK version that matches its spec. */
|
|
40838
|
+
async embedValues(values) {
|
|
40845
40839
|
if (typeof this.embedder === `undefined`) throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
|
|
40846
40840
|
const isFastEmbed = this.embedder.provider === `fastembed`;
|
|
40847
40841
|
if (isFastEmbed && this.firstEmbed instanceof Promise) await this.firstEmbed;
|
|
40848
40842
|
const options = {
|
|
40849
|
-
values
|
|
40843
|
+
values,
|
|
40850
40844
|
maxRetries: 3
|
|
40851
40845
|
};
|
|
40852
40846
|
const model = this.embedder;
|
|
@@ -40881,106 +40875,87 @@ ${workingMemory}`;
|
|
|
40881
40875
|
}
|
|
40882
40876
|
if (isFastEmbed && !this.firstEmbed) this.firstEmbed = promise;
|
|
40883
40877
|
const { embeddings, usage } = await promise;
|
|
40884
|
-
|
|
40878
|
+
return {
|
|
40885
40879
|
embeddings,
|
|
40886
|
-
|
|
40887
|
-
usage,
|
|
40888
|
-
dimension: embeddings[0]?.length
|
|
40880
|
+
usage
|
|
40889
40881
|
};
|
|
40890
|
-
this.embeddingCache.set(key, result);
|
|
40891
|
-
return result;
|
|
40892
40882
|
}
|
|
40893
|
-
|
|
40883
|
+
/**
|
|
40884
|
+
* Metadata of each thread, spread onto that thread's vector rows so `semanticRecall.filter`
|
|
40885
|
+
* can match thread attributes.
|
|
40886
|
+
*/
|
|
40887
|
+
async loadThreadMetadata(threadIds) {
|
|
40888
|
+
const memoryStore = await this.getMemoryStore();
|
|
40889
|
+
const metadataByThread = /* @__PURE__ */ new Map();
|
|
40890
|
+
await Promise.all(threadIds.map(async (threadId) => {
|
|
40891
|
+
try {
|
|
40892
|
+
const thread = await memoryStore.getThreadById({ threadId });
|
|
40893
|
+
if (thread?.metadata) metadataByThread.set(threadId, thread.metadata);
|
|
40894
|
+
} catch (error) {
|
|
40895
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
40896
|
+
throw new Error(`Could not fetch metadata for thread ${threadId} while writing semantic recall embeddings: ${message}`);
|
|
40897
|
+
}
|
|
40898
|
+
}));
|
|
40899
|
+
return metadataByThread;
|
|
40900
|
+
}
|
|
40901
|
+
/**
|
|
40902
|
+
* Embeds messages into vector rows in the shared format, without writing them. Every
|
|
40903
|
+
* message-vector write in this class builds its rows here.
|
|
40904
|
+
*/
|
|
40905
|
+
async buildMessageVectorRows({ items, embeddedMessages }) {
|
|
40906
|
+
if (items.length === 0) return {
|
|
40907
|
+
ids: [],
|
|
40908
|
+
metadata: [],
|
|
40909
|
+
embeddedEntries: []
|
|
40910
|
+
};
|
|
40911
|
+
if (!this.embedder && !this.isSelfEmbedding) throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
|
|
40912
|
+
return buildMessageEmbeddingRows({
|
|
40913
|
+
items,
|
|
40914
|
+
embed: this.isSelfEmbedding ? void 0 : (chunks) => this.embedValues(chunks),
|
|
40915
|
+
maxChunkChars: resolveMaxChunkChars({
|
|
40916
|
+
maxChunkChars: this.configuredMaxChunkChars,
|
|
40917
|
+
embedder: this.embedder
|
|
40918
|
+
}),
|
|
40919
|
+
loadThreadMetadata: (threadIds) => this.loadThreadMetadata(threadIds),
|
|
40920
|
+
embeddedMessages,
|
|
40921
|
+
indexName: embeddedMessages ? this.getEmbeddingIndexName(this.isSelfEmbedding ? void 0 : await this.getEmbeddingDimension()) : void 0
|
|
40922
|
+
});
|
|
40923
|
+
}
|
|
40924
|
+
/** Writes rows from {@link buildMessageVectorRows} into the message index for `config`. */
|
|
40925
|
+
async writeMessageVectorRows({ rows, config, embeddedMessages }) {
|
|
40926
|
+
if (!this.vector || rows.ids.length === 0) return;
|
|
40927
|
+
const { indexName } = await this.createEmbeddingIndex(rows.dimension, config);
|
|
40928
|
+
await upsertMessageVectors(this.vector, indexName, rows, embeddedMessages);
|
|
40929
|
+
}
|
|
40930
|
+
/**
|
|
40931
|
+
* Embeds messages and writes their vector rows.
|
|
40932
|
+
*
|
|
40933
|
+
* @returns Tokens billed by the embedder, if any.
|
|
40934
|
+
*/
|
|
40935
|
+
async writeMessageVectors(args) {
|
|
40936
|
+
if (!this.vector) return void 0;
|
|
40937
|
+
const rows = await this.buildMessageVectorRows(args);
|
|
40938
|
+
await this.writeMessageVectorRows({
|
|
40939
|
+
...args,
|
|
40940
|
+
rows
|
|
40941
|
+
});
|
|
40942
|
+
return rows.usage;
|
|
40943
|
+
}
|
|
40944
|
+
async saveMessages({ messages, memoryConfig, observabilityContext, embeddedMessages }) {
|
|
40894
40945
|
const span = this.createMemorySpan("save", observabilityContext, void 0, { messageCount: messages.length });
|
|
40895
40946
|
try {
|
|
40896
40947
|
const updatedMessages = this.prepareMessagesForPersistence(messages);
|
|
40897
40948
|
const config = this.getMergedThreadConfig(memoryConfig);
|
|
40898
40949
|
const dbMessages = new MessageList({ generateMessageId: () => this.generateId() }).add(updatedMessages, "memory").get.all.db();
|
|
40899
|
-
const
|
|
40900
|
-
const
|
|
40901
|
-
|
|
40902
|
-
|
|
40903
|
-
|
|
40904
|
-
|
|
40905
|
-
if (message.threadId) {
|
|
40906
|
-
if (!messagesByThread.has(message.threadId)) messagesByThread.set(message.threadId, []);
|
|
40907
|
-
messagesByThread.get(message.threadId).push(message);
|
|
40908
|
-
}
|
|
40909
|
-
});
|
|
40910
|
-
const threadMetadataMap = /* @__PURE__ */ new Map();
|
|
40911
|
-
await Promise.all(Array.from(messagesByThread.keys()).map(async (threadId) => {
|
|
40912
|
-
try {
|
|
40913
|
-
const thread = await memoryStore.getThreadById({ threadId });
|
|
40914
|
-
if (thread?.metadata) threadMetadataMap.set(threadId, thread.metadata);
|
|
40915
|
-
} catch (error) {
|
|
40916
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
40917
|
-
throw new Error(`Could not fetch metadata for thread ${threadId} while saving semantic recall embeddings: ${message}`);
|
|
40918
|
-
}
|
|
40919
|
-
}));
|
|
40920
|
-
const embeddingData = [];
|
|
40921
|
-
let dimension;
|
|
40922
|
-
await Promise.all(updatedMessages.map(async (message) => {
|
|
40923
|
-
let textForEmbedding = null;
|
|
40924
|
-
if (message.content.content && typeof message.content.content === "string" && message.content.content.trim() !== "") textForEmbedding = message.content.content;
|
|
40925
|
-
else if (message.content.parts && message.content.parts.length > 0) {
|
|
40926
|
-
const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim();
|
|
40927
|
-
if (joined) textForEmbedding = joined;
|
|
40928
|
-
}
|
|
40929
|
-
if (!textForEmbedding) return;
|
|
40930
|
-
let embeddings = [];
|
|
40931
|
-
let documents;
|
|
40932
|
-
let chunks;
|
|
40933
|
-
if (this.isSelfEmbedding) {
|
|
40934
|
-
chunks = this.chunkText(textForEmbedding);
|
|
40935
|
-
documents = chunks;
|
|
40936
|
-
} else {
|
|
40937
|
-
const result = await this.embedMessageContent(textForEmbedding);
|
|
40938
|
-
dimension = result.dimension;
|
|
40939
|
-
if (result.usage?.tokens) totalTokens += result.usage.tokens;
|
|
40940
|
-
embeddings = result.embeddings;
|
|
40941
|
-
chunks = result.chunks;
|
|
40942
|
-
}
|
|
40943
|
-
const threadMetadata = message.threadId ? threadMetadataMap.get(message.threadId) || {} : {};
|
|
40944
|
-
embeddingData.push({
|
|
40945
|
-
embeddings,
|
|
40946
|
-
documents,
|
|
40947
|
-
metadata: chunks.map(() => ({
|
|
40948
|
-
...threadMetadata,
|
|
40949
|
-
message_id: message.id,
|
|
40950
|
-
thread_id: message.threadId,
|
|
40951
|
-
resource_id: message.resourceId,
|
|
40952
|
-
role: message.role,
|
|
40953
|
-
content: textForEmbedding,
|
|
40954
|
-
created_at: message.createdAt instanceof Date ? message.createdAt.toISOString() : String(message.createdAt)
|
|
40955
|
-
}))
|
|
40956
|
-
});
|
|
40957
|
-
}));
|
|
40958
|
-
if (embeddingData.length > 0 && (this.isSelfEmbedding || dimension !== void 0)) {
|
|
40959
|
-
if (typeof this.vector === `undefined`) throw new Error(`Tried to upsert embeddings but this Memory instance doesn't have an attached vector db.`);
|
|
40960
|
-
const { indexName } = await this.createEmbeddingIndex(dimension, config);
|
|
40961
|
-
const allVectors = [];
|
|
40962
|
-
const allMetadata = [];
|
|
40963
|
-
const allDocuments = [];
|
|
40964
|
-
for (const data of embeddingData) {
|
|
40965
|
-
allVectors.push(...data.embeddings);
|
|
40966
|
-
if (data.documents) allDocuments.push(...data.documents);
|
|
40967
|
-
allMetadata.push(...data.metadata);
|
|
40968
|
-
}
|
|
40969
|
-
if (this.isSelfEmbedding) await this.vector.upsert({
|
|
40970
|
-
indexName,
|
|
40971
|
-
documents: allDocuments,
|
|
40972
|
-
metadata: allMetadata
|
|
40973
|
-
});
|
|
40974
|
-
else await this.vector.upsert({
|
|
40975
|
-
indexName,
|
|
40976
|
-
vectors: allVectors,
|
|
40977
|
-
metadata: allMetadata
|
|
40978
|
-
});
|
|
40979
|
-
}
|
|
40980
|
-
}
|
|
40950
|
+
const result = await (await this.getMemoryStore()).saveMessages({ messages: dbMessages });
|
|
40951
|
+
const usage = this.vector && config.semanticRecall ? await this.writeMessageVectors({
|
|
40952
|
+
items: updatedMessages.map((message) => ({ message })),
|
|
40953
|
+
config,
|
|
40954
|
+
embeddedMessages
|
|
40955
|
+
}) : void 0;
|
|
40981
40956
|
const saveResult = {
|
|
40982
40957
|
...result,
|
|
40983
|
-
usage
|
|
40958
|
+
usage
|
|
40984
40959
|
};
|
|
40985
40960
|
span?.end({
|
|
40986
40961
|
output: { success: true },
|
|
@@ -41703,51 +41678,6 @@ Notes:
|
|
|
41703
41678
|
return collected;
|
|
41704
41679
|
}
|
|
41705
41680
|
/**
|
|
41706
|
-
* Index a list of messages directly (without querying storage).
|
|
41707
|
-
* Used by observe-time indexing to vectorize newly-observed messages.
|
|
41708
|
-
*/
|
|
41709
|
-
async indexMessagesList(messages) {
|
|
41710
|
-
if (!this.vector || !this.embedder) return;
|
|
41711
|
-
const embeddingData = [];
|
|
41712
|
-
let dimension;
|
|
41713
|
-
await Promise.all(messages.map(async (message) => {
|
|
41714
|
-
let textForEmbedding = null;
|
|
41715
|
-
if (message.content.content && typeof message.content.content === "string" && message.content.content.trim() !== "") textForEmbedding = message.content.content;
|
|
41716
|
-
else if (message.content.parts && message.content.parts.length > 0) {
|
|
41717
|
-
const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim();
|
|
41718
|
-
if (joined) textForEmbedding = joined;
|
|
41719
|
-
}
|
|
41720
|
-
if (!textForEmbedding) return;
|
|
41721
|
-
const embedResult = await this.embedMessageContent(textForEmbedding);
|
|
41722
|
-
dimension = embedResult.dimension;
|
|
41723
|
-
embeddingData.push({
|
|
41724
|
-
embeddings: embedResult.embeddings,
|
|
41725
|
-
metadata: embedResult.chunks.map(() => ({
|
|
41726
|
-
message_id: message.id,
|
|
41727
|
-
thread_id: message.threadId,
|
|
41728
|
-
resource_id: message.resourceId,
|
|
41729
|
-
role: message.role,
|
|
41730
|
-
content: textForEmbedding,
|
|
41731
|
-
created_at: message.createdAt instanceof Date ? message.createdAt.toISOString() : String(message.createdAt)
|
|
41732
|
-
}))
|
|
41733
|
-
});
|
|
41734
|
-
}));
|
|
41735
|
-
if (embeddingData.length > 0 && dimension !== void 0) {
|
|
41736
|
-
const { indexName } = await this.createEmbeddingIndex(dimension);
|
|
41737
|
-
const allVectors = [];
|
|
41738
|
-
const allMetadata = [];
|
|
41739
|
-
for (const data of embeddingData) {
|
|
41740
|
-
allVectors.push(...data.embeddings);
|
|
41741
|
-
allMetadata.push(...data.metadata);
|
|
41742
|
-
}
|
|
41743
|
-
await this.vector.upsert({
|
|
41744
|
-
indexName,
|
|
41745
|
-
vectors: allVectors,
|
|
41746
|
-
metadata: allMetadata
|
|
41747
|
-
});
|
|
41748
|
-
}
|
|
41749
|
-
}
|
|
41750
|
-
/**
|
|
41751
41681
|
* Check whether retrieval search (vector-based) is enabled.
|
|
41752
41682
|
* Returns true when `retrieval: { vector: true }` and Memory has a vector store plus either an
|
|
41753
41683
|
* embedder or a store that generates embeddings itself.
|
|
@@ -41853,43 +41783,19 @@ Notes:
|
|
|
41853
41783
|
const messagesWithTextUpdates = [...textForEmbeddingById.keys()].map((id) => ({ id }));
|
|
41854
41784
|
if (messagesWithTextUpdates.length > 0) {
|
|
41855
41785
|
const existingMessagesMap = new Map(existing.messages.map((m) => [m.id, m]));
|
|
41856
|
-
const
|
|
41857
|
-
|
|
41858
|
-
const
|
|
41859
|
-
|
|
41860
|
-
|
|
41861
|
-
|
|
41862
|
-
|
|
41863
|
-
|
|
41864
|
-
|
|
41865
|
-
|
|
41866
|
-
|
|
41867
|
-
|
|
41868
|
-
|
|
41869
|
-
chunks = this.chunkText(textForEmbedding);
|
|
41870
|
-
documents = chunks;
|
|
41871
|
-
} else {
|
|
41872
|
-
const result = await this.embedMessageContent(textForEmbedding);
|
|
41873
|
-
dimension = result.dimension;
|
|
41874
|
-
embeddings = result.embeddings;
|
|
41875
|
-
chunks = result.chunks;
|
|
41876
|
-
}
|
|
41877
|
-
embeddingData.push({
|
|
41878
|
-
embeddings,
|
|
41879
|
-
documents,
|
|
41880
|
-
metadata: chunks.map(() => ({
|
|
41881
|
-
message_id: message.id,
|
|
41882
|
-
thread_id: existingMessage.threadId,
|
|
41883
|
-
resource_id: existingMessage.resourceId,
|
|
41884
|
-
role: existingMessage.role,
|
|
41885
|
-
content: textForEmbedding,
|
|
41886
|
-
created_at: existingMessage.createdAt instanceof Date ? existingMessage.createdAt.toISOString() : String(existingMessage.createdAt)
|
|
41887
|
-
}))
|
|
41888
|
-
});
|
|
41889
|
-
messageIdsWithNewEmbeddings.add(message.id);
|
|
41890
|
-
} else messageIdsWithClearedContent.add(message.id);
|
|
41891
|
-
}));
|
|
41892
|
-
const messageIdsNeedingDeletion = /* @__PURE__ */ new Set([...messageIdsWithClearedContent, ...messageIdsWithNewEmbeddings]);
|
|
41786
|
+
const messageIdsNeedingDeletion = /* @__PURE__ */ new Set();
|
|
41787
|
+
const items = [];
|
|
41788
|
+
for (const { id } of messagesWithTextUpdates) {
|
|
41789
|
+
const existingMessage = existingMessagesMap.get(id);
|
|
41790
|
+
if (!existingMessage) continue;
|
|
41791
|
+
messageIdsNeedingDeletion.add(id);
|
|
41792
|
+
const text = textForEmbeddingById.get(id);
|
|
41793
|
+
if (text) items.push({
|
|
41794
|
+
message: existingMessage,
|
|
41795
|
+
text
|
|
41796
|
+
});
|
|
41797
|
+
}
|
|
41798
|
+
const rows = await this.buildMessageVectorRows({ items });
|
|
41893
41799
|
if (messageIdsNeedingDeletion.size > 0) try {
|
|
41894
41800
|
const memoryIndexes = await this.getMemoryVectorIndexes([this.messageIndexPrefix]);
|
|
41895
41801
|
const idsToDelete = [...messageIdsNeedingDeletion];
|
|
@@ -41912,27 +41818,10 @@ Notes:
|
|
|
41912
41818
|
} catch {
|
|
41913
41819
|
this.logger.debug("Failed to clean up old vectors during message update");
|
|
41914
41820
|
}
|
|
41915
|
-
|
|
41916
|
-
|
|
41917
|
-
|
|
41918
|
-
|
|
41919
|
-
const allDocuments = [];
|
|
41920
|
-
for (const data of embeddingData) {
|
|
41921
|
-
allVectors.push(...data.embeddings);
|
|
41922
|
-
if (data.documents) allDocuments.push(...data.documents);
|
|
41923
|
-
allMetadata.push(...data.metadata);
|
|
41924
|
-
}
|
|
41925
|
-
if (this.isSelfEmbedding) await this.vector.upsert({
|
|
41926
|
-
indexName,
|
|
41927
|
-
documents: allDocuments,
|
|
41928
|
-
metadata: allMetadata
|
|
41929
|
-
});
|
|
41930
|
-
else await this.vector.upsert({
|
|
41931
|
-
indexName,
|
|
41932
|
-
vectors: allVectors,
|
|
41933
|
-
metadata: allMetadata
|
|
41934
|
-
});
|
|
41935
|
-
}
|
|
41821
|
+
await this.writeMessageVectorRows({
|
|
41822
|
+
rows,
|
|
41823
|
+
config
|
|
41824
|
+
});
|
|
41936
41825
|
}
|
|
41937
41826
|
}
|
|
41938
41827
|
return memoryStore.updateMessages({ messages });
|
|
@@ -42197,6 +42086,7 @@ Notes:
|
|
|
42197
42086
|
threadId,
|
|
42198
42087
|
perPage: false
|
|
42199
42088
|
});
|
|
42089
|
+
const rows = await this.buildMessageVectorRows({ items: messages.map((message) => ({ message })) });
|
|
42200
42090
|
const messageIndexes = await this.getMemoryVectorIndexes([this.messageIndexPrefix]);
|
|
42201
42091
|
await Promise.all(messageIndexes.map(async (indexName) => {
|
|
42202
42092
|
await this.vector.deleteVectors({
|
|
@@ -42204,7 +42094,10 @@ Notes:
|
|
|
42204
42094
|
filter: { thread_id: threadId }
|
|
42205
42095
|
});
|
|
42206
42096
|
}));
|
|
42207
|
-
|
|
42097
|
+
await this.writeMessageVectorRows({
|
|
42098
|
+
rows,
|
|
42099
|
+
config
|
|
42100
|
+
});
|
|
42208
42101
|
} catch (error) {
|
|
42209
42102
|
this.logger.error("Failed to migrate semantic-recall vectors during thread transfer", {
|
|
42210
42103
|
threadId,
|
|
@@ -42352,67 +42245,15 @@ Notes:
|
|
|
42352
42245
|
return cloned;
|
|
42353
42246
|
}
|
|
42354
42247
|
/**
|
|
42355
|
-
* Embed cloned messages for semantic recall.
|
|
42356
|
-
*
|
|
42248
|
+
* Embed cloned messages for semantic recall. Cloned messages have new ids, so they get rows of
|
|
42249
|
+
* their own next to the source thread's rows.
|
|
42357
42250
|
*/
|
|
42358
42251
|
async embedClonedMessages(messages, config) {
|
|
42359
42252
|
if (!this.vector || !this.embedder && !this.isSelfEmbedding) return;
|
|
42360
|
-
|
|
42361
|
-
|
|
42362
|
-
|
|
42363
|
-
|
|
42364
|
-
if (message.content?.content && typeof message.content.content === "string" && message.content.content.trim() !== "") textForEmbedding = message.content.content;
|
|
42365
|
-
else if (message.content?.parts && message.content.parts.length > 0) {
|
|
42366
|
-
const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim();
|
|
42367
|
-
if (joined) textForEmbedding = joined;
|
|
42368
|
-
}
|
|
42369
|
-
if (!textForEmbedding) return;
|
|
42370
|
-
let embeddings = [];
|
|
42371
|
-
let documents;
|
|
42372
|
-
let chunks;
|
|
42373
|
-
if (this.isSelfEmbedding) {
|
|
42374
|
-
chunks = this.chunkText(textForEmbedding);
|
|
42375
|
-
documents = chunks;
|
|
42376
|
-
} else {
|
|
42377
|
-
const result = await this.embedMessageContent(textForEmbedding);
|
|
42378
|
-
dimension = result.dimension;
|
|
42379
|
-
embeddings = result.embeddings;
|
|
42380
|
-
chunks = result.chunks;
|
|
42381
|
-
}
|
|
42382
|
-
embeddingData.push({
|
|
42383
|
-
embeddings,
|
|
42384
|
-
documents,
|
|
42385
|
-
metadata: chunks.map(() => ({
|
|
42386
|
-
message_id: message.id,
|
|
42387
|
-
thread_id: message.threadId,
|
|
42388
|
-
resource_id: message.resourceId,
|
|
42389
|
-
role: message.role,
|
|
42390
|
-
content: textForEmbedding,
|
|
42391
|
-
created_at: message.createdAt instanceof Date ? message.createdAt.toISOString() : String(message.createdAt)
|
|
42392
|
-
}))
|
|
42393
|
-
});
|
|
42394
|
-
}));
|
|
42395
|
-
if (embeddingData.length > 0 && (this.isSelfEmbedding || dimension !== void 0)) {
|
|
42396
|
-
const { indexName } = await this.createEmbeddingIndex(dimension, config);
|
|
42397
|
-
const allVectors = [];
|
|
42398
|
-
const allMetadata = [];
|
|
42399
|
-
const allDocuments = [];
|
|
42400
|
-
for (const data of embeddingData) {
|
|
42401
|
-
allVectors.push(...data.embeddings);
|
|
42402
|
-
if (data.documents) allDocuments.push(...data.documents);
|
|
42403
|
-
allMetadata.push(...data.metadata);
|
|
42404
|
-
}
|
|
42405
|
-
if (this.isSelfEmbedding) await this.vector.upsert({
|
|
42406
|
-
indexName,
|
|
42407
|
-
documents: allDocuments,
|
|
42408
|
-
metadata: allMetadata
|
|
42409
|
-
});
|
|
42410
|
-
else await this.vector.upsert({
|
|
42411
|
-
indexName,
|
|
42412
|
-
vectors: allVectors,
|
|
42413
|
-
metadata: allMetadata
|
|
42414
|
-
});
|
|
42415
|
-
}
|
|
42253
|
+
await this.writeMessageVectors({
|
|
42254
|
+
items: messages.map((message) => ({ message })),
|
|
42255
|
+
config
|
|
42256
|
+
});
|
|
42416
42257
|
}
|
|
42417
42258
|
/**
|
|
42418
42259
|
* Get the clone metadata from a thread if it was cloned from another thread.
|
|
@@ -42596,4 +42437,4 @@ Notes:
|
|
|
42596
42437
|
};
|
|
42597
42438
|
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 };
|
|
42598
42439
|
|
|
42599
|
-
//# sourceMappingURL=src-
|
|
42440
|
+
//# sourceMappingURL=src-BL6KZcyR.js.map
|