@mastra/memory 1.36.0-alpha.0 → 1.36.0-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.
@@ -3712,7 +3712,7 @@ function trimStartOfStream() {
3712
3712
  };
3713
3713
  }
3714
3714
  //#endregion
3715
- //#region ../_vendored/ai_v5/dist/dist-DqVGDtnX.js
3715
+ //#region ../_vendored/ai_v5/dist/dist-CwCWl16R.js
3716
3716
  var marker$2$4 = "vercel.ai.error";
3717
3717
  var symbol$2$4 = Symbol.for(marker$2$4);
3718
3718
  var _a$2$4;
@@ -8999,7 +8999,7 @@ var object$1 = ({ schema: inputSchema }) => {
8999
8999
  };
9000
9000
  };
9001
9001
  //#endregion
9002
- //#region ../_vendored/ai_v6/dist/dist-BcG-LFmj.js
9002
+ //#region ../_vendored/ai_v6/dist/dist-B5Rt0qDx.js
9003
9003
  var marker$2 = "vercel.ai.error";
9004
9004
  var symbol$2 = Symbol.for(marker$2);
9005
9005
  var _a$2;
@@ -11544,7 +11544,7 @@ var _b14;
11544
11544
  }
11545
11545
  });
11546
11546
  //#endregion
11547
- //#region ../_vendored/ai_v6/dist/dist-t-eoX9xC.js
11547
+ //#region ../_vendored/ai_v6/dist/dist-BgUIUei9.js
11548
11548
  function getContext() {
11549
11549
  return { headers: {} };
11550
11550
  }
@@ -22180,6 +22180,7 @@ function serializeNonImageFilePartForTokenCounting(part) {
22180
22180
  function isValidCacheEntry(entry, expectedKey, expectedSource) {
22181
22181
  return Boolean(entry && entry.v === TOKEN_ESTIMATE_CACHE_VERSION && entry.source === expectedSource && entry.key === expectedKey && Number.isFinite(entry.tokens));
22182
22182
  }
22183
+ const modelContextStorage = new AsyncLocalStorage();
22183
22184
  function parseModelContext(model) {
22184
22185
  if (!model) return void 0;
22185
22186
  if (typeof model === "object") return model.provider || model.modelId ? {
@@ -22801,7 +22802,6 @@ async function fetchGoogleAttachmentTokenEstimate(modelId, part) {
22801
22802
  var TokenCounter = class TokenCounter {
22802
22803
  cacheSource;
22803
22804
  defaultModelContext;
22804
- modelContextStorage = new AsyncLocalStorage();
22805
22805
  inFlightAttachmentCounts = /* @__PURE__ */ new Map();
22806
22806
  multimodalToolResultCounts = /* @__PURE__ */ new WeakMap();
22807
22807
  static TOKENS_PER_MESSAGE = 3.8;
@@ -22811,10 +22811,12 @@ var TokenCounter = class TokenCounter {
22811
22811
  this.defaultModelContext = parseModelContext(options?.model);
22812
22812
  }
22813
22813
  runWithModelContext(model, fn) {
22814
- return this.modelContextStorage.run(parseModelContext(model), fn);
22814
+ const contexts = new Map(modelContextStorage.getStore());
22815
+ contexts.set(this, parseModelContext(model));
22816
+ return modelContextStorage.run(contexts, fn);
22815
22817
  }
22816
22818
  getModelContext() {
22817
- return this.modelContextStorage.getStore() ?? this.defaultModelContext;
22819
+ return modelContextStorage.getStore()?.get(this) ?? this.defaultModelContext;
22818
22820
  }
22819
22821
  /**
22820
22822
  * Count tokens in a plain string
@@ -28018,7 +28020,7 @@ var ObservationStep = class {
28018
28020
  if (obsResult.succeeded) {
28019
28021
  observed = true;
28020
28022
  didThresholdCleanup = true;
28021
- const observedIds = obsResult.activatedMessageIds ?? obsResult.record.observedMessageIds ?? [];
28023
+ const observedIds = obsResult.cleanupMessageIds;
28022
28024
  const minRemaining = resolveRetentionFloor(om.getObservationConfig().bufferActivation ?? 1, statusSnapshot.threshold);
28023
28025
  await om.cleanupMessages({
28024
28026
  threadId,
@@ -28085,8 +28087,8 @@ var ObservationStep = class {
28085
28087
  }
28086
28088
  /**
28087
28089
  * Run the full threshold observation pipeline:
28088
- * waitForBuffering → re-check → activate → reflect → observe (sync fallback when
28089
- * buffered activation did not happen)
28090
+ * waitForBuffering → re-check → activate buffered chunks → reflect → observe
28091
+ * (sync fallback when pending tokens are still at or above the threshold)
28090
28092
  */
28091
28093
  async runThresholdObservation() {
28092
28094
  const { threadId, resourceId, messageList } = this.turn;
@@ -28094,59 +28096,76 @@ var ObservationStep = class {
28094
28096
  await om.waitForBuffering(threadId, resourceId);
28095
28097
  await this.turn.refreshRecord();
28096
28098
  const observableMessages = this.seededResponseMessage ? getObservableMessages(messageList).filter((msg) => msg.id !== this.turn.responseMessageId) : getObservableMessages(messageList);
28097
- const freshStatus = await om.getStatus({
28099
+ let status = await om.getStatus({
28098
28100
  threadId,
28099
28101
  resourceId,
28100
28102
  record: this.turn.record,
28101
28103
  messages: observableMessages
28102
28104
  });
28103
- if (!freshStatus.shouldObserve) return {
28105
+ if (!status.shouldObserve) return {
28104
28106
  succeeded: false,
28105
- record: freshStatus.record
28107
+ record: status.record,
28108
+ cleanupMessageIds: []
28106
28109
  };
28107
- if (freshStatus.canActivate) {
28110
+ let pendingMessages = observableMessages;
28111
+ const activatedMessageIds = [];
28112
+ let activated = false;
28113
+ while (status.shouldObserve && status.canActivate) {
28108
28114
  const activation = await om.activate({
28109
28115
  threadId,
28110
28116
  resourceId,
28111
28117
  record: this.turn.record,
28112
- messages: observableMessages,
28118
+ messages: pendingMessages,
28119
+ pendingTokens: status.pendingTokens,
28113
28120
  currentModel: this.turn.actorModelContext,
28114
28121
  writer: this.turn.writer,
28115
28122
  messageList
28116
28123
  });
28117
28124
  this.turn.setRecord(activation.record);
28118
- if (activation.activated) {
28119
- const postActivationRecord = activation.record;
28120
- await om.reflector.maybeReflect({
28121
- record: postActivationRecord,
28122
- observationTokens: postActivationRecord.observationTokenCount ?? 0,
28125
+ if (!activation.activated) break;
28126
+ activated = true;
28127
+ const ids = new Set(activation.activatedMessageIds ?? []);
28128
+ activatedMessageIds.push(...ids);
28129
+ pendingMessages = pendingMessages.filter((msg) => !ids.has(msg.id));
28130
+ status = await om.getStatus({
28131
+ threadId,
28132
+ resourceId,
28133
+ record: this.turn.record,
28134
+ messages: pendingMessages
28135
+ });
28136
+ }
28137
+ if (activated) {
28138
+ const postActivationRecord = this.turn.record;
28139
+ await om.reflector.maybeReflect({
28140
+ record: postActivationRecord,
28141
+ observationTokens: postActivationRecord.observationTokenCount ?? 0,
28142
+ threadId,
28143
+ writer: this.turn.writer,
28144
+ messageList,
28145
+ currentModel: this.turn.actorModelContext,
28146
+ requestContext: this.turn.requestContext,
28147
+ observabilityContext: this.turn.observabilityContext,
28148
+ lastActivityAt: getLastActivityFromMessages(getObservableMessages(messageList)),
28149
+ reflectionHooks: om.composeHooks(void 0, {
28123
28150
  threadId,
28124
- writer: this.turn.writer,
28125
- messageList,
28126
- currentModel: this.turn.actorModelContext,
28127
- requestContext: this.turn.requestContext,
28128
- observabilityContext: this.turn.observabilityContext,
28129
- lastActivityAt: getLastActivityFromMessages(getObservableMessages(messageList)),
28130
- reflectionHooks: om.composeHooks(void 0, {
28131
- threadId,
28132
- resourceId,
28133
- trigger: "turn-sync"
28134
- }),
28151
+ resourceId,
28135
28152
  trigger: "turn-sync"
28136
- });
28137
- return {
28138
- succeeded: true,
28139
- record: activation.record,
28140
- activatedMessageIds: activation.activatedMessageIds
28141
- };
28142
- }
28153
+ }),
28154
+ trigger: "turn-sync"
28155
+ });
28156
+ if (!status.shouldObserve) return {
28157
+ succeeded: true,
28158
+ record: postActivationRecord,
28159
+ activatedMessageIds,
28160
+ cleanupMessageIds: activatedMessageIds
28161
+ };
28143
28162
  }
28144
28163
  let obsResult;
28145
28164
  try {
28146
28165
  obsResult = await om.observe({
28147
28166
  threadId,
28148
28167
  resourceId,
28149
- messages: observableMessages,
28168
+ messages: pendingMessages,
28150
28169
  messageList,
28151
28170
  trigger: "turn-sync",
28152
28171
  agent: this.turn.agent,
@@ -28159,8 +28178,10 @@ var ObservationStep = class {
28159
28178
  } catch (error) {
28160
28179
  if (om.config.observation.failurePolicy !== "continue" || !isOmModelExecutionError(error) || error.failureKind !== "observer-model") throw error;
28161
28180
  return {
28162
- succeeded: false,
28163
- record: freshStatus.record
28181
+ succeeded: activated,
28182
+ record: this.turn.record,
28183
+ activatedMessageIds: activated ? activatedMessageIds : void 0,
28184
+ cleanupMessageIds: activatedMessageIds
28164
28185
  };
28165
28186
  }
28166
28187
  if (obsResult.observed) {
@@ -28187,8 +28208,10 @@ var ObservationStep = class {
28187
28208
  if (messagesToSeal.length > 0) await om.persistMessages(messagesToSeal, threadId, resourceId);
28188
28209
  }
28189
28210
  return {
28190
- succeeded: obsResult.observed,
28211
+ succeeded: activated || obsResult.observed,
28191
28212
  record: obsResult.record,
28213
+ activatedMessageIds: activated ? activatedMessageIds : void 0,
28214
+ cleanupMessageIds: [.../* @__PURE__ */ new Set([...activatedMessageIds, ...obsResult.observed ? obsResult.record.observedMessageIds ?? [] : []])],
28192
28215
  observerExchange: om.observer.lastExchange
28193
28216
  };
28194
28217
  }
@@ -31876,6 +31899,7 @@ ${formattedMessages}
31876
31899
  let activateAfterIdleExpiredMs;
31877
31900
  let previousModel;
31878
31901
  let currentModel;
31902
+ let livePendingTokens = opts.pendingTokens;
31879
31903
  if (opts.checkThreshold) {
31880
31904
  const thresholdMessages = opts.messages ?? await this.loadMessagesFromStorage(threadId, resourceId, record.lastObservedAt ? new Date(record.lastObservedAt) : void 0);
31881
31905
  const activateAfterIdle = resolveActivationTTL(this.observationConfig.activateAfterIdle, opts.currentModel);
@@ -31904,6 +31928,7 @@ ${formattedMessages}
31904
31928
  activated: false,
31905
31929
  record
31906
31930
  };
31931
+ livePendingTokens ??= status.pendingTokens;
31907
31932
  }
31908
31933
  }
31909
31934
  if (record.isBufferingObservation) {
@@ -31927,8 +31952,9 @@ ${formattedMessages}
31927
31952
  const messageTokensThreshold = getMaxThreshold(this.getEffectiveMessageTokens(freshRecord));
31928
31953
  const activationRatio = resolveActivationRatio(this.observationConfig.bufferActivation ?? .7, messageTokensThreshold);
31929
31954
  const totalChunkMessageTokens = freshChunks.reduce((sum, c) => sum + (c.messageTokens ?? 0), 0);
31930
- const currentPendingTokens = freshRecord.pendingMessageTokens || totalChunkMessageTokens;
31955
+ const currentPendingTokens = livePendingTokens ?? (freshRecord.pendingMessageTokens || totalChunkMessageTokens);
31931
31956
  const forceMaxActivation = !!(this.observationConfig.blockAfter && currentPendingTokens >= this.observationConfig.blockAfter);
31957
+ if (freshRecord.pendingMessageTokens !== currentPendingTokens) await this.storage.setPendingMessageTokens(freshRecord.id, currentPendingTokens);
31932
31958
  const activationResult = await this.storage.swapBufferedToActive({
31933
31959
  id: freshRecord.id,
31934
31960
  activationRatio,
@@ -33273,22 +33299,32 @@ var Memory = class Memory extends MastraMemory {
33273
33299
  if (resourceScope && !resourceId && config?.semanticRecall && vectorSearchString) throw new Error("Memory error: Resource-scoped semantic recall is enabled but no resourceId was provided. Either provide a resourceId or explicitly set semanticRecall.scope to 'thread'.");
33274
33300
  let usage;
33275
33301
  if (config?.semanticRecall && vectorSearchString && this.vector) {
33276
- const result = await this.embedMessageContent(vectorSearchString);
33277
- usage = result.usage;
33278
- const { embeddings, dimension } = result;
33279
- const { indexName } = await this.createEmbeddingIndex(dimension, config);
33280
- await Promise.all(embeddings.map(async (embedding) => {
33281
- if (typeof this.vector === `undefined`) throw new Error(`Tried to query vector index ${indexName} but this Memory instance doesn't have an attached vector db.`);
33282
- const scopeFilter = resourceScope ? { resource_id: resourceId } : { thread_id: threadId };
33283
- const userFilter = typeof config.semanticRecall === "object" ? config.semanticRecall.filter : void 0;
33284
- const combinedFilter = userFilter ? { $and: [scopeFilter, userFilter] } : scopeFilter;
33302
+ const scopeFilter = resourceScope ? { resource_id: resourceId } : { thread_id: threadId };
33303
+ const userFilter = typeof config.semanticRecall === "object" ? config.semanticRecall.filter : void 0;
33304
+ const combinedFilter = userFilter ? { $and: [scopeFilter, userFilter] } : scopeFilter;
33305
+ if (this.isSelfEmbedding) {
33306
+ const { indexName } = await this.createEmbeddingIndex(void 0, config);
33285
33307
  vectorResults.push(...await this.vector.query({
33286
33308
  indexName,
33287
- queryVector: embedding,
33309
+ queryText: vectorSearchString,
33288
33310
  topK: vectorConfig.topK,
33289
33311
  filter: combinedFilter
33290
33312
  }));
33291
- }));
33313
+ } else {
33314
+ const result = await this.embedMessageContent(vectorSearchString);
33315
+ usage = result.usage;
33316
+ const { embeddings, dimension } = result;
33317
+ const { indexName } = await this.createEmbeddingIndex(dimension, config);
33318
+ await Promise.all(embeddings.map(async (embedding) => {
33319
+ if (typeof this.vector === `undefined`) throw new Error(`Tried to query vector index ${indexName} but this Memory instance doesn't have an attached vector db.`);
33320
+ vectorResults.push(...await this.vector.query({
33321
+ indexName,
33322
+ queryVector: embedding,
33323
+ topK: vectorConfig.topK,
33324
+ filter: combinedFilter
33325
+ }));
33326
+ }));
33327
+ }
33292
33328
  }
33293
33329
  const threshold = (typeof config.semanticRecall === "object" ? config.semanticRecall : void 0)?.threshold;
33294
33330
  const filteredVectorResults = threshold !== void 0 ? vectorResults.filter((r) => r.score >= threshold) : vectorResults;
@@ -33446,11 +33482,13 @@ var Memory = class Memory extends MastraMemory {
33446
33482
  if (this.vector) this.trackVectorCleanup(this.deleteThreadVectors(threadId));
33447
33483
  }
33448
33484
  /**
33449
- * Prefix shared by every message index. The index for the default embedding
33450
- * dimension is named with the bare prefix; other dimensions add a suffix.
33485
+ * Prefix shared by every message index. The index for the default embedding dimension is named
33486
+ * with the bare prefix; other dimensions add a dimension suffix, and a store that embeds the
33487
+ * text itself adds its own. Built here rather than read from `getEmbeddingIndexName()`, which
33488
+ * answers for one configuration and so would not match indexes written under another.
33451
33489
  */
33452
33490
  get messageIndexPrefix() {
33453
- return this.getEmbeddingIndexName();
33491
+ return `memory${this.vector?.indexSeparator ?? "_"}messages`;
33454
33492
  }
33455
33493
  /**
33456
33494
  * Prefix shared by every observation index. Each observation index adds a dimension suffix.
@@ -33735,13 +33773,24 @@ ${workingMemory}`;
33735
33773
  if (joined) textForEmbedding = joined;
33736
33774
  }
33737
33775
  if (!textForEmbedding) return;
33738
- const result = await this.embedMessageContent(textForEmbedding);
33739
- dimension = result.dimension;
33740
- if (result.usage?.tokens) totalTokens += result.usage.tokens;
33776
+ let embeddings = [];
33777
+ let documents;
33778
+ let chunks;
33779
+ if (this.isSelfEmbedding) {
33780
+ chunks = this.chunkText(textForEmbedding);
33781
+ documents = chunks;
33782
+ } else {
33783
+ const result = await this.embedMessageContent(textForEmbedding);
33784
+ dimension = result.dimension;
33785
+ if (result.usage?.tokens) totalTokens += result.usage.tokens;
33786
+ embeddings = result.embeddings;
33787
+ chunks = result.chunks;
33788
+ }
33741
33789
  const threadMetadata = message.threadId ? threadMetadataMap.get(message.threadId) || {} : {};
33742
33790
  embeddingData.push({
33743
- embeddings: result.embeddings,
33744
- metadata: result.chunks.map(() => ({
33791
+ embeddings,
33792
+ documents,
33793
+ metadata: chunks.map(() => ({
33745
33794
  ...threadMetadata,
33746
33795
  message_id: message.id,
33747
33796
  thread_id: message.threadId,
@@ -33752,16 +33801,23 @@ ${workingMemory}`;
33752
33801
  }))
33753
33802
  });
33754
33803
  }));
33755
- if (embeddingData.length > 0 && dimension !== void 0) {
33804
+ if (embeddingData.length > 0 && (this.isSelfEmbedding || dimension !== void 0)) {
33756
33805
  if (typeof this.vector === `undefined`) throw new Error(`Tried to upsert embeddings but this Memory instance doesn't have an attached vector db.`);
33757
33806
  const { indexName } = await this.createEmbeddingIndex(dimension, config);
33758
33807
  const allVectors = [];
33759
33808
  const allMetadata = [];
33809
+ const allDocuments = [];
33760
33810
  for (const data of embeddingData) {
33761
33811
  allVectors.push(...data.embeddings);
33812
+ if (data.documents) allDocuments.push(...data.documents);
33762
33813
  allMetadata.push(...data.metadata);
33763
33814
  }
33764
- await this.vector.upsert({
33815
+ if (this.isSelfEmbedding) await this.vector.upsert({
33816
+ indexName,
33817
+ documents: allDocuments,
33818
+ metadata: allMetadata
33819
+ });
33820
+ else await this.vector.upsert({
33765
33821
  indexName,
33766
33822
  vectors: allVectors,
33767
33823
  metadata: allMetadata
@@ -34546,11 +34602,22 @@ Notes:
34546
34602
  }
34547
34603
  }
34548
34604
  if (textForEmbedding) {
34549
- const result = await this.embedMessageContent(textForEmbedding);
34550
- dimension = result.dimension;
34605
+ let embeddings = [];
34606
+ let documents;
34607
+ let chunks;
34608
+ if (this.isSelfEmbedding) {
34609
+ chunks = this.chunkText(textForEmbedding);
34610
+ documents = chunks;
34611
+ } else {
34612
+ const result = await this.embedMessageContent(textForEmbedding);
34613
+ dimension = result.dimension;
34614
+ embeddings = result.embeddings;
34615
+ chunks = result.chunks;
34616
+ }
34551
34617
  embeddingData.push({
34552
- embeddings: result.embeddings,
34553
- metadata: result.chunks.map(() => ({
34618
+ embeddings,
34619
+ documents,
34620
+ metadata: chunks.map(() => ({
34554
34621
  message_id: message.id,
34555
34622
  thread_id: existingMessage.threadId,
34556
34623
  resource_id: existingMessage.resourceId,
@@ -34585,15 +34652,22 @@ Notes:
34585
34652
  } catch {
34586
34653
  this.logger.debug("Failed to clean up old vectors during message update");
34587
34654
  }
34588
- if (embeddingData.length > 0 && dimension !== void 0) {
34655
+ if (embeddingData.length > 0 && (this.isSelfEmbedding || dimension !== void 0)) {
34589
34656
  const { indexName } = await this.createEmbeddingIndex(dimension, config);
34590
34657
  const allVectors = [];
34591
34658
  const allMetadata = [];
34659
+ const allDocuments = [];
34592
34660
  for (const data of embeddingData) {
34593
34661
  allVectors.push(...data.embeddings);
34662
+ if (data.documents) allDocuments.push(...data.documents);
34594
34663
  allMetadata.push(...data.metadata);
34595
34664
  }
34596
- await this.vector.upsert({
34665
+ if (this.isSelfEmbedding) await this.vector.upsert({
34666
+ indexName,
34667
+ documents: allDocuments,
34668
+ metadata: allMetadata
34669
+ });
34670
+ else await this.vector.upsert({
34597
34671
  indexName,
34598
34672
  vectors: allVectors,
34599
34673
  metadata: allMetadata
@@ -34780,7 +34854,7 @@ Notes:
34780
34854
  await this.rollbackCopiedThread(memoryStore, result.thread, "OM clone", false, priorDestinationResourceWm);
34781
34855
  throw error;
34782
34856
  }
34783
- if (this.vector && this.embedder && config.semanticRecall) try {
34857
+ if (this.vector && (this.embedder || this.isSelfEmbedding) && config.semanticRecall) try {
34784
34858
  await this.embedCopiedMessagesInBatches(memoryStore, result, config);
34785
34859
  } catch (error) {
34786
34860
  await this.rollbackCopiedThread(memoryStore, result.thread, "embedding", true, priorDestinationResourceWm);
@@ -34849,7 +34923,7 @@ Notes:
34849
34923
  async updateThreadResourceId({ threadId, resourceId, memoryConfig }) {
34850
34924
  const memoryStore = await this.getMemoryStore();
34851
34925
  const config = this.getMergedThreadConfig(memoryConfig);
34852
- const migratesVectors = Boolean(this.vector && this.embedder && config.semanticRecall);
34926
+ const migratesVectors = Boolean(this.vector && (this.embedder || this.isSelfEmbedding) && config.semanticRecall);
34853
34927
  if (!migratesVectors) {
34854
34928
  const existing = await memoryStore.getThreadById({ threadId });
34855
34929
  if (existing && existing.resourceId === resourceId) return existing;
@@ -34955,7 +35029,7 @@ Notes:
34955
35029
  * This is similar to the embedding logic in saveMessages but operates on already-saved messages.
34956
35030
  */
34957
35031
  async embedClonedMessages(messages, config) {
34958
- if (!this.vector || !this.embedder) return;
35032
+ if (!this.vector || !this.embedder && !this.isSelfEmbedding) return;
34959
35033
  const embeddingData = [];
34960
35034
  let dimension;
34961
35035
  await Promise.all(messages.map(async (message) => {
@@ -34966,11 +35040,22 @@ Notes:
34966
35040
  if (joined) textForEmbedding = joined;
34967
35041
  }
34968
35042
  if (!textForEmbedding) return;
34969
- const result = await this.embedMessageContent(textForEmbedding);
34970
- dimension = result.dimension;
35043
+ let embeddings = [];
35044
+ let documents;
35045
+ let chunks;
35046
+ if (this.isSelfEmbedding) {
35047
+ chunks = this.chunkText(textForEmbedding);
35048
+ documents = chunks;
35049
+ } else {
35050
+ const result = await this.embedMessageContent(textForEmbedding);
35051
+ dimension = result.dimension;
35052
+ embeddings = result.embeddings;
35053
+ chunks = result.chunks;
35054
+ }
34971
35055
  embeddingData.push({
34972
- embeddings: result.embeddings,
34973
- metadata: result.chunks.map(() => ({
35056
+ embeddings,
35057
+ documents,
35058
+ metadata: chunks.map(() => ({
34974
35059
  message_id: message.id,
34975
35060
  thread_id: message.threadId,
34976
35061
  resource_id: message.resourceId,
@@ -34980,15 +35065,22 @@ Notes:
34980
35065
  }))
34981
35066
  });
34982
35067
  }));
34983
- if (embeddingData.length > 0 && dimension !== void 0) {
35068
+ if (embeddingData.length > 0 && (this.isSelfEmbedding || dimension !== void 0)) {
34984
35069
  const { indexName } = await this.createEmbeddingIndex(dimension, config);
34985
35070
  const allVectors = [];
34986
35071
  const allMetadata = [];
35072
+ const allDocuments = [];
34987
35073
  for (const data of embeddingData) {
34988
35074
  allVectors.push(...data.embeddings);
35075
+ if (data.documents) allDocuments.push(...data.documents);
34989
35076
  allMetadata.push(...data.metadata);
34990
35077
  }
34991
- await this.vector.upsert({
35078
+ if (this.isSelfEmbedding) await this.vector.upsert({
35079
+ indexName,
35080
+ documents: allDocuments,
35081
+ metadata: allMetadata
35082
+ });
35083
+ else await this.vector.upsert({
34992
35084
  indexName,
34993
35085
  vectors: allVectors,
34994
35086
  metadata: allMetadata
@@ -35184,4 +35276,4 @@ Notes:
35184
35276
  //#endregion
35185
35277
  export { formatMessagesForObserver as A, OBSERVATION_CONTEXT_PROMPT_THREAD as B, SUMMARIZE_THREAD_DEFAULTS as C, buildObserverPrompt as D, OBSERVER_SYSTEM_PROMPT as E, parseAnchorId as F, StaleKnowledgeSemanticIndexError as G, getObservationContextPrompt as H, stripEphemeralAnchorIds as I, SUBCONSCIOUS_ACTIVITY_STATE_ID as J, SubconsciousRemindExtractor as K, OBSERVATIONAL_MEMORY_DEFAULTS as L, optimizeObservationsForContext as M, parseObserverOutput as N, buildObserverSystemPrompt as O, injectAnchorIds as P, Extractor as Q, OBSERVATION_CONTEXT_INSTRUCTIONS as R, deepMergeWorkingMemory as S, TokenCounter as T, Subconscious as U, OBSERVATION_CONTINUATION_HINT as V, KnowledgeSemanticIndexCoordinator as W, publishSubconsciousActivity as X, buildSubconsciousActivitySnapshot as Y, renderSubconsciousActivity as Z, reconcileObservationGroupsFromReflection as _, extractWorkingMemoryContent as a, wrapInObservationGroup as b, getObservationsAsOf as c, WORKING_MEMORY_STATE_ID as d, WORKING_MEMORY_STATE_PROCESSOR_ID as f, parseObservationGroups as g, deriveObservationGroupProvenance as h, WorkingMemory as i, hasCurrentTaskSection as j, extractCurrentTask as k, ObservationalMemoryProcessor as l, combineObservationGroupRanges as m, MessageHistory$1 as n, extractWorkingMemoryTags as o, WorkingMemoryStateProcessor as p, ModelByInputTokens as q, SemanticRecall as r, removeWorkingMemoryTags as s, Memory as t, ObservationalMemory as u, renderObservationGroupsForReflection as v, summarizeConversation as w, WorkingMemoryExtractor as x, stripObservationGroups as y, OBSERVATION_CONTEXT_PROMPT as z };
35186
35278
 
35187
- //# sourceMappingURL=src-BV9eXuMM.js.map
35279
+ //# sourceMappingURL=src-BxI-PDpC.js.map