@mastra/memory 1.31.0-alpha.2 → 1.31.0

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.
@@ -19,7 +19,6 @@ import { join } from "path";
19
19
  import { createTool } from "@mastra/core/tools";
20
20
  import { MASTRA_THREAD_ID_KEY, RequestContext } from "@mastra/core/request-context";
21
21
  import { modelSupportsAttachments, modelSupportsTemperature, resolveModelConfig } from "@mastra/core/llm";
22
- import { estimateTokenCount } from "tokenx";
23
22
  import { AsyncLocalStorage } from "async_hooks";
24
23
  import probeImageSizeSync from "probe-image-size/sync.js";
25
24
  import { isStandardSchemaWithJSON as isStandardSchemaWithJSON$1, toStandardSchema as toStandardSchema$1 } from "@mastra/core/schema";
@@ -3713,7 +3712,7 @@ function trimStartOfStream() {
3713
3712
  };
3714
3713
  }
3715
3714
  //#endregion
3716
- //#region ../_vendored/ai_v5/dist/dist-DCHMJHX3.js
3715
+ //#region ../_vendored/ai_v5/dist/dist-CQthBS6n.js
3717
3716
  var marker$1$4 = "vercel.ai.error";
3718
3717
  var symbol$1$3 = Symbol.for(marker$1$4);
3719
3718
  var _a$1$3;
@@ -8602,7 +8601,7 @@ var object$1 = ({ schema: inputSchema }) => {
8602
8601
  };
8603
8602
  };
8604
8603
  //#endregion
8605
- //#region ../_vendored/ai_v6/dist/dist-Cx98_f-i.js
8604
+ //#region ../_vendored/ai_v6/dist/dist-BJ8L5vTo.js
8606
8605
  var marker$1 = "vercel.ai.error";
8607
8606
  var symbol$1$1 = Symbol.for(marker$1);
8608
8607
  var _a$1$1;
@@ -10755,7 +10754,7 @@ function withoutTrailingSlash(url) {
10755
10754
  return url == null ? void 0 : url.replace(/\/$/, "");
10756
10755
  }
10757
10756
  //#endregion
10758
- //#region ../_vendored/ai_v6/dist/dist-pa8X6y1Z.js
10757
+ //#region ../_vendored/ai_v6/dist/dist-Smko-YXk.js
10759
10758
  function getContext() {
10760
10759
  return { headers: {} };
10761
10760
  }
@@ -18304,6 +18303,62 @@ function safeSlice(str, end) {
18304
18303
  return str.slice(0, safeEnd);
18305
18304
  }
18306
18305
  //#endregion
18306
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/tokenx/1.3.0/09093cdaeebfe25c39ba9052d6277b45fc99abf5e14e859f60f338f5c5160afd/node_modules/tokenx/dist/index.mjs
18307
+ const PATTERNS = {
18308
+ whitespace: /^\s+$/,
18309
+ cjk: /[\u4E00-\u9FFF\u3400-\u4DBF\u3000-\u303F\uFF00-\uFFEF\u30A0-\u30FF\u2E80-\u2EFF\u31C0-\u31EF\u3200-\u32FF\u3300-\u33FF\uAC00-\uD7AF\u1100-\u11FF\u3130-\u318F\uA960-\uA97F\uD7B0-\uD7FF]/,
18310
+ numeric: /^\d+(?:[.,]\d+)*$/,
18311
+ punctuation: /[.,!?;(){}[\]<>:/\\|@#$%^&*+=`~_-]/,
18312
+ alphanumeric: /^[a-zA-Z0-9\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]+$/
18313
+ };
18314
+ const TOKEN_SPLIT_PATTERN = /* @__PURE__ */ new RegExp(`(\\s+|${PATTERNS.punctuation.source}+)`);
18315
+ const DEFAULT_CHARS_PER_TOKEN = 6;
18316
+ const SHORT_TOKEN_THRESHOLD = 3;
18317
+ const DEFAULT_LANGUAGE_CONFIGS = [
18318
+ {
18319
+ pattern: /[äöüßẞ]/i,
18320
+ averageCharsPerToken: 3
18321
+ },
18322
+ {
18323
+ pattern: /[éèêëàâîïôûùüÿçœæáíóúñ]/i,
18324
+ averageCharsPerToken: 3
18325
+ },
18326
+ {
18327
+ pattern: /[ąćęłńóśźżěščřžýůúďťň]/i,
18328
+ averageCharsPerToken: 3.5
18329
+ }
18330
+ ];
18331
+ /**
18332
+ * Estimates the number of tokens in a text string using heuristic rules.
18333
+ */
18334
+ function estimateTokenCount(text, options = {}) {
18335
+ if (!text) return 0;
18336
+ const { defaultCharsPerToken = DEFAULT_CHARS_PER_TOKEN, languageConfigs = DEFAULT_LANGUAGE_CONFIGS } = options;
18337
+ const segments = text.split(TOKEN_SPLIT_PATTERN).filter(Boolean);
18338
+ let tokenCount = 0;
18339
+ for (const segment of segments) tokenCount += estimateSegmentTokens(segment, languageConfigs, defaultCharsPerToken);
18340
+ return tokenCount;
18341
+ }
18342
+ function estimateSegmentTokens(segment, languageConfigs, defaultCharsPerToken) {
18343
+ if (PATTERNS.whitespace.test(segment)) return 0;
18344
+ if (PATTERNS.cjk.test(segment)) return getCharacterCount(segment);
18345
+ if (PATTERNS.numeric.test(segment)) return 1;
18346
+ if (segment.length <= SHORT_TOKEN_THRESHOLD) return 1;
18347
+ if (PATTERNS.punctuation.test(segment)) return segment.length > 1 ? Math.ceil(segment.length / 2) : 1;
18348
+ if (PATTERNS.alphanumeric.test(segment)) {
18349
+ const charsPerToken$1 = getLanguageSpecificCharsPerToken(segment, languageConfigs) ?? defaultCharsPerToken;
18350
+ return Math.ceil(segment.length / charsPerToken$1);
18351
+ }
18352
+ const charsPerToken = getLanguageSpecificCharsPerToken(segment, languageConfigs) ?? defaultCharsPerToken;
18353
+ return Math.ceil(segment.length / charsPerToken);
18354
+ }
18355
+ function getLanguageSpecificCharsPerToken(segment, languageConfigs) {
18356
+ for (const config of languageConfigs) if (config.pattern.test(segment)) return config.averageCharsPerToken;
18357
+ }
18358
+ function getCharacterCount(text) {
18359
+ return Array.from(text).length;
18360
+ }
18361
+ //#endregion
18307
18362
  //#region src/processors/observational-memory/tool-argument-helpers.ts
18308
18363
  const DEFAULT_OBSERVER_TOOL_ARGUMENT_MAX_TOKENS = 2e3;
18309
18364
  const OBSERVER_TOOL_ARGUMENT_INLINE_STRING_MAX_CHARS = 160;
@@ -25160,6 +25215,10 @@ var SyncObservationStrategy = class extends ObservationStrategy {
25160
25215
  async persist(processed) {
25161
25216
  const { record, threadId, resourceId, messages } = this.opts;
25162
25217
  const thread = await this.storage.getThreadById({ threadId });
25218
+ if (!await this.storage.getObservationalMemory(record.threadId, record.resourceId)) {
25219
+ omDebug(`[OM:sync-obs] skipping persist for thread ${threadId}: observational memory record is gone`);
25220
+ return;
25221
+ }
25163
25222
  let threadUpdateMarker;
25164
25223
  if (thread) {
25165
25224
  const oldTitle = thread.title?.trim();
@@ -25341,6 +25400,10 @@ var AsyncBufferObservationStrategy = class extends ObservationStrategy {
25341
25400
  async persist(processed) {
25342
25401
  if (!processed.observations) return;
25343
25402
  const { record, threadId, resourceId, messages } = this.opts;
25403
+ if (!await this.storage.getObservationalMemory(record.threadId, record.resourceId)) {
25404
+ omDebug(`[OM:asyncBuffer] skipping persist for thread ${threadId}: observational memory record is gone`);
25405
+ return;
25406
+ }
25344
25407
  const messageTokens = await this.tokenCounter.countMessagesAsync(messages);
25345
25408
  await withRetry(() => this.storage.updateBufferedObservations({
25346
25409
  id: record.id,
@@ -26334,6 +26397,10 @@ var ObservationTurn = class {
26334
26397
  if (!this._context) throw new Error("Turn not started — call start() first");
26335
26398
  return this._context;
26336
26399
  }
26400
+ /** Whether the turn has been ended and can no longer accept steps. */
26401
+ get ended() {
26402
+ return this._ended;
26403
+ }
26337
26404
  /** The current step, if one exists. */
26338
26405
  get currentStep() {
26339
26406
  return this._currentStep;
@@ -30070,9 +30137,11 @@ ${formattedMessages}
30070
30137
  let lifecycleError;
30071
30138
  let observationStarted = false;
30072
30139
  let generationBefore = -1;
30140
+ let recordInsideLock;
30073
30141
  try {
30074
30142
  await this.withLock(lockKey, async () => {
30075
30143
  const freshRecord = await this.getOrCreateRecord(threadId, resourceId);
30144
+ recordInsideLock = freshRecord;
30076
30145
  generationBefore = freshRecord.generationCount;
30077
30146
  const unobservedMessages = messages ? this.getUnobservedMessages(messages, freshRecord) : await this.loadMessagesFromStorage(threadId, resourceId, freshRecord.lastObservedAt ? new Date(freshRecord.lastObservedAt) : void 0);
30078
30147
  if (!this.meetsObservationThreshold({
@@ -30115,7 +30184,7 @@ ${formattedMessages}
30115
30184
  omDebug(`[OM:hooks] onObservationEnd hook failed after cycle failure: ${endHookError instanceof Error ? endHookError.message : String(endHookError)}`);
30116
30185
  }
30117
30186
  if (lifecycleError !== void 0) throw lifecycleError;
30118
- const record = await this.getOrCreateRecord(threadId, resourceId);
30187
+ const record = await this.getRecord(threadId, resourceId) ?? recordInsideLock;
30119
30188
  const reflected = record.generationCount > generationBefore && generationBefore >= 0;
30120
30189
  return {
30121
30190
  observed,
@@ -30596,6 +30665,10 @@ var ObservationalMemoryProcessor = class {
30596
30665
  if (this.turn === activeTurn) this.turn = void 0;
30597
30666
  state.__omTurn = void 0;
30598
30667
  }
30668
+ if (activeTurn?.ended || this.turn?.ended) {
30669
+ if (this.turn?.ended) this.turn = void 0;
30670
+ state.__omTurn = void 0;
30671
+ }
30599
30672
  if (!this.turn || !state.__omTurn) {
30600
30673
  if (this.turn && !state.__omTurn) await this.turn.end().catch(() => {});
30601
30674
  this.turn = this.engine.beginTurn({
@@ -30696,11 +30769,11 @@ var ObservationalMemoryProcessor = class {
30696
30769
  return this.engine.getTokenCounter().runWithModelContext(state.__omActorModelContext, async () => {
30697
30770
  if (parseMemoryRequestContext(requestContext)?.memoryConfig?.readOnly) return messageList;
30698
30771
  const turn = asLiveTurn(state.__omTurn) ?? this.turn;
30699
- if (turn) {
30700
- await turn.end();
30701
- this.turn = void 0;
30702
- state.__omTurn = void 0;
30703
- } else {
30772
+ const liveTurn = turn && !turn.ended ? turn : void 0;
30773
+ if (liveTurn) await liveTurn.end();
30774
+ this.turn = void 0;
30775
+ state.__omTurn = void 0;
30776
+ if (!liveTurn) {
30704
30777
  const newOutput = messageList.get.response.db();
30705
30778
  const messagesToSave = [...messageList.get.input.db(), ...newOutput];
30706
30779
  if (messagesToSave.length > 0 && context.threadId) await this.engine.persistMessages(messagesToSave, context.threadId, context.resourceId);
@@ -30910,6 +30983,7 @@ const DEFAULT_MESSAGE_RANGE = {
30910
30983
  };
30911
30984
  const DEFAULT_TOP_K = 4;
30912
30985
  const VECTOR_DELETE_BATCH_SIZE = 100;
30986
+ const OM_DELETE_DRAIN_TIMEOUT_MS = 1e4;
30913
30987
  const DEFAULT_EMBEDDING_CACHE_MAX_SIZE = 1e3;
30914
30988
  /**
30915
30989
  * Gives Mastra agents conversation history, with optional working memory,
@@ -31361,6 +31435,8 @@ var Memory = class Memory extends MastraMemory {
31361
31435
  await this.deleteStoredThread(memoryStore, threadId, thread?.resourceId);
31362
31436
  }
31363
31437
  async deleteStoredThread(memoryStore, threadId, resourceId) {
31438
+ const engine = this._omEngine ? await this._omEngine : this._omEngineInstance;
31439
+ if (engine && resourceId) await engine.waitForBuffering(threadId, resourceId, OM_DELETE_DRAIN_TIMEOUT_MS);
31364
31440
  await memoryStore.deleteThread({ threadId });
31365
31441
  if (resourceId && memoryStore.supportsObservationalMemory) await memoryStore.clearObservationalMemory(threadId, resourceId);
31366
31442
  if (this.vector) this.trackVectorCleanup(this.deleteThreadVectors(threadId));
@@ -33094,4 +33170,4 @@ Notes:
33094
33170
  //#endregion
33095
33171
  export { formatMessagesForObserver as A, OBSERVATION_CONTINUATION_HINT as B, SUMMARIZE_THREAD_DEFAULTS as C, buildObserverPrompt as D, OBSERVER_SYSTEM_PROMPT as E, parseAnchorId as F, ModelByInputTokens as G, KnowledgeSemanticIndexCoordinator as H, stripEphemeralAnchorIds as I, publishSubconsciousActivity as J, SUBCONSCIOUS_ACTIVITY_STATE_ID as K, OBSERVATIONAL_MEMORY_DEFAULTS as L, optimizeObservationsForContext as M, parseObserverOutput as N, buildObserverSystemPrompt as O, injectAnchorIds as P, OBSERVATION_CONTEXT_INSTRUCTIONS as R, WorkingMemoryExtractor as S, TokenCounter as T, StaleKnowledgeSemanticIndexError as U, Subconscious as V, SubconsciousRemindExtractor as W, Extractor as X, renderSubconsciousActivity as Y, wrapInObservationGroup as _, extractWorkingMemoryContent as a, WorkingMemoryStateProcessor as b, getObservationsAsOf as c, combineObservationGroupRanges as d, deriveObservationGroupProvenance as f, stripObservationGroups as g, renderObservationGroupsForReflection as h, WorkingMemory as i, hasCurrentTaskSection as j, extractCurrentTask as k, ObservationalMemoryProcessor as l, reconcileObservationGroupsFromReflection as m, MessageHistory$1 as n, extractWorkingMemoryTags as o, parseObservationGroups as p, buildSubconsciousActivitySnapshot as q, SemanticRecall as r, removeWorkingMemoryTags as s, Memory as t, ObservationalMemory as u, WORKING_MEMORY_STATE_ID as v, summarizeConversation as w, deepMergeWorkingMemory as x, WORKING_MEMORY_STATE_PROCESSOR_ID as y, OBSERVATION_CONTEXT_PROMPT as z };
33096
33172
 
33097
- //# sourceMappingURL=src-DquR-jTR.js.map
33173
+ //# sourceMappingURL=src-zTE4189S.js.map