@mastra/memory 1.38.0-alpha.0 → 1.39.0-alpha.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.
@@ -19804,21 +19804,22 @@ function safeSlice(str, end) {
19804
19804
  return str.slice(0, safeEnd);
19805
19805
  }
19806
19806
  //#endregion
19807
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/tokenx/1.3.0/09093cdaeebfe25c39ba9052d6277b45fc99abf5e14e859f60f338f5c5160afd/node_modules/tokenx/dist/index.mjs
19807
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/tokenx/1.6.0/394289cb1bed8c542941f77748eea1a31bd3419018d0fb2ac7029ece2458cdd1/node_modules/tokenx/dist/index.mjs
19808
19808
  const PATTERNS = {
19809
19809
  whitespace: /^\s+$/,
19810
- 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]/,
19811
- numeric: /^\d+(?:[.,]\d+)*$/,
19812
- punctuation: /[.,!?;(){}[\]<>:/\\|@#$%^&*+=`~_-]/,
19813
- alphanumeric: /^[a-zA-Z0-9\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]+$/
19810
+ structuredWhitespace: /\n\s/,
19811
+ cjk: /[\u4E00-\u9FFF\u3400-\u4DBF\u3000-\u30FF\uFF00-\uFFEF\u2E80-\u2EFF\u31C0-\u31EF\u3200-\u32FF\u3300-\u33FF\uAC00-\uD7AF\u1100-\u11FF\u3130-\u318F\uA960-\uA97F\uD7B0-\uD7FF]/,
19812
+ numeric: /^\d+$/,
19813
+ punctuation: /[.,!?;(){}[\]<>:/\\|@#$%^&*+=`~_"-]/
19814
19814
  };
19815
- const TOKEN_SPLIT_PATTERN = /* @__PURE__ */ new RegExp(`(\\s+|${PATTERNS.punctuation.source}+)`);
19815
+ const TOKEN_SPLIT_PATTERN = new RegExp(`(\\s+|${PATTERNS.punctuation.source}+)`);
19816
19816
  const DEFAULT_CHARS_PER_TOKEN = 6;
19817
19817
  const SHORT_TOKEN_THRESHOLD = 3;
19818
+ const KANA_CHARS_PER_TOKEN = 1.35;
19818
19819
  const DEFAULT_LANGUAGE_CONFIGS = [
19819
19820
  {
19820
19821
  pattern: /[äöüßẞ]/i,
19821
- averageCharsPerToken: 3
19822
+ averageCharsPerToken: 2.6
19822
19823
  },
19823
19824
  {
19824
19825
  pattern: /[éèêëàâîïôûùüÿçœæáíóúñ]/i,
@@ -19826,39 +19827,75 @@ const DEFAULT_LANGUAGE_CONFIGS = [
19826
19827
  },
19827
19828
  {
19828
19829
  pattern: /[ąćęłńóśźżěščřžýůúďťň]/i,
19829
- averageCharsPerToken: 3.5
19830
+ averageCharsPerToken: 2.5
19831
+ },
19832
+ {
19833
+ pattern: /[\u0430-\u044F\u0451]/i,
19834
+ averageCharsPerToken: 4
19835
+ },
19836
+ {
19837
+ pattern: /[\u03AC-\u03CE]/i,
19838
+ averageCharsPerToken: 2.75
19839
+ },
19840
+ {
19841
+ pattern: /^\p{Extended_Pictographic}[\p{Extended_Pictographic}\p{Emoji_Component}]*$/u,
19842
+ averageCharsPerToken: .75
19830
19843
  }
19831
19844
  ];
19832
19845
  /**
19833
- * Estimates the number of tokens in a text string using heuristic rules.
19846
+ * Walks a text as (segment, estimated token count) pairs. The segments
19847
+ * concatenate back to the original text; whitespace segments count zero
19848
+ * tokens unless they carry structure (indentation or blank lines).
19834
19849
  */
19835
- function estimateTokenCount(text, options = {}) {
19836
- if (!text) return 0;
19837
- const { defaultCharsPerToken = DEFAULT_CHARS_PER_TOKEN, languageConfigs = DEFAULT_LANGUAGE_CONFIGS } = options;
19838
- const segments = text.split(TOKEN_SPLIT_PATTERN).filter(Boolean);
19839
- let tokenCount = 0;
19840
- for (const segment of segments) tokenCount += estimateSegmentTokens(segment, languageConfigs, defaultCharsPerToken);
19841
- return tokenCount;
19850
+ function* walkSegments(text, options = {}) {
19851
+ if (!text) return;
19852
+ const resolvedOptions = resolveOptions(options);
19853
+ for (const segment of text.split(TOKEN_SPLIT_PATTERN)) if (segment) yield {
19854
+ segment,
19855
+ tokenCount: estimateSegmentTokens(segment, resolvedOptions)
19856
+ };
19857
+ }
19858
+ function resolveOptions(options) {
19859
+ return {
19860
+ defaultCharsPerToken: options.defaultCharsPerToken ?? DEFAULT_CHARS_PER_TOKEN,
19861
+ languageConfigs: options.languageConfigs ?? DEFAULT_LANGUAGE_CONFIGS
19862
+ };
19842
19863
  }
19843
- function estimateSegmentTokens(segment, languageConfigs, defaultCharsPerToken) {
19844
- if (PATTERNS.whitespace.test(segment)) return 0;
19845
- if (PATTERNS.cjk.test(segment)) return getCharacterCount(segment);
19846
- if (PATTERNS.numeric.test(segment)) return 1;
19864
+ function estimateSegmentTokens(segment, { languageConfigs, defaultCharsPerToken }) {
19865
+ if (PATTERNS.whitespace.test(segment)) return PATTERNS.structuredWhitespace.test(segment) ? 1 : 0;
19866
+ const languageCharsPerToken = getLanguageSpecificCharsPerToken(segment, languageConfigs);
19867
+ if (languageCharsPerToken !== void 0) return Math.ceil(getCharacterCount(segment) / languageCharsPerToken);
19868
+ if (PATTERNS.cjk.test(segment)) return estimateCjkTokens(segment);
19869
+ if (PATTERNS.numeric.test(segment)) return Math.ceil(segment.length / 3);
19847
19870
  if (segment.length <= SHORT_TOKEN_THRESHOLD) return 1;
19848
- if (PATTERNS.punctuation.test(segment)) return segment.length > 1 ? Math.ceil(segment.length / 2) : 1;
19849
- if (PATTERNS.alphanumeric.test(segment)) {
19850
- const charsPerToken$1 = getLanguageSpecificCharsPerToken(segment, languageConfigs) ?? defaultCharsPerToken;
19851
- return Math.ceil(segment.length / charsPerToken$1);
19852
- }
19853
- const charsPerToken = getLanguageSpecificCharsPerToken(segment, languageConfigs) ?? defaultCharsPerToken;
19854
- return Math.ceil(segment.length / charsPerToken);
19871
+ if (PATTERNS.punctuation.test(segment)) return Math.ceil(segment.length / 2);
19872
+ return Math.ceil(segment.length / defaultCharsPerToken);
19855
19873
  }
19856
19874
  function getLanguageSpecificCharsPerToken(segment, languageConfigs) {
19857
- for (const config of languageConfigs) if (config.pattern.test(segment)) return config.averageCharsPerToken;
19875
+ for (const config of languageConfigs) if (segment.search(config.pattern) !== -1) return config.averageCharsPerToken;
19858
19876
  }
19859
19877
  function getCharacterCount(text) {
19860
19878
  return Array.from(text).length;
19861
19879
  }
19880
+ function estimateCjkTokens(segment) {
19881
+ let kanaCount = 0;
19882
+ let otherCount = 0;
19883
+ for (const character of segment) {
19884
+ const codePoint = character.codePointAt(0);
19885
+ if (codePoint >= 12352 && codePoint <= 12543) kanaCount++;
19886
+ else otherCount++;
19887
+ }
19888
+ return otherCount + Math.ceil(kanaCount / KANA_CHARS_PER_TOKEN);
19889
+ }
19890
+ /**
19891
+ * Estimates the number of tokens in a text string using heuristic rules
19892
+ */
19893
+ function estimateTokenCount(text, options = {}) {
19894
+ if (!text) return 0;
19895
+ let tokenCount = 0;
19896
+ for (const segmentEstimate of walkSegments(text, options)) tokenCount += segmentEstimate.tokenCount;
19897
+ return tokenCount;
19898
+ }
19862
19899
  //#endregion
19863
19900
  //#region src/processors/observational-memory/tool-argument-helpers.ts
19864
19901
  const DEFAULT_OBSERVER_TOOL_ARGUMENT_MAX_TOKENS = 2e3;
@@ -22379,7 +22416,7 @@ const IMAGE_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
22379
22416
  "heif",
22380
22417
  "avif"
22381
22418
  ]);
22382
- const TOKEN_ESTIMATE_CACHE_VERSION = 7;
22419
+ const TOKEN_ESTIMATE_CACHE_VERSION = 8;
22383
22420
  /**
22384
22421
  * Cache `source` marker for token estimates supplied by the caller via
22385
22422
  * `part.providerMetadata.mastra.tokenEstimate`. Pipelines that strip the real
@@ -26480,7 +26517,8 @@ function hasGoogleGenerativeAIKey() {
26480
26517
  /**
26481
26518
  * Resolve the concrete model ID `'auto'` selects for a main model ID.
26482
26519
  *
26483
- * Order: Gemini when `GOOGLE_GENERATIVE_AI_API_KEY` is set; else the main provider's low-cost
26520
+ * Order: Gemini when Google is usable (`canUseProvider('google')`, or `GOOGLE_GENERATIVE_AI_API_KEY`
26521
+ * when no check is given); else the main provider's low-cost
26484
26522
  * model (keeping a `mastra/` gateway prefix); else the main model ID itself. Returns `undefined`
26485
26523
  * only when there is no Google key and no main model ID.
26486
26524
  */
@@ -26489,7 +26527,7 @@ function resolveAutoModelId(mainModelId, options) {
26489
26527
  ...AUTO_MODEL_BY_PROVIDER,
26490
26528
  ...options?.autoModels
26491
26529
  };
26492
- if (hasGoogleGenerativeAIKey() && models.google) return models.google;
26530
+ if ((options?.canUseProvider ? options.canUseProvider("google") : hasGoogleGenerativeAIKey()) && models.google) return models.google;
26493
26531
  if (!mainModelId) return;
26494
26532
  const prefix = mainModelId.startsWith(ROUTE_PREFIX) ? ROUTE_PREFIX : "";
26495
26533
  const provider = mainModelId.slice(prefix.length).split("/", 1)[0];
@@ -31170,6 +31208,7 @@ var ObservationalMemory = class ObservationalMemory {
31170
31208
  mastra;
31171
31209
  autoModels;
31172
31210
  resolveAutoModelHook;
31211
+ canUseProvider;
31173
31212
  memory;
31174
31213
  /**
31175
31214
  * Track message IDs observed during this instance's lifetime.
@@ -31268,6 +31307,7 @@ var ObservationalMemory = class ObservationalMemory {
31268
31307
  this.hooks = config.hooks;
31269
31308
  this.autoModels = config.autoModels;
31270
31309
  this.resolveAutoModelHook = config.resolveModel;
31310
+ this.canUseProvider = config.canUseProvider;
31271
31311
  this.hookExecution = config.hookExecution ?? "non-blocking";
31272
31312
  this.mastra = config.mastra;
31273
31313
  this.memory = config.memory;
@@ -31467,11 +31507,18 @@ var ObservationalMemory = class ObservationalMemory {
31467
31507
  model: await this.resolveAutoModel(options)
31468
31508
  };
31469
31509
  }
31510
+ autoModelOptions(requestContext) {
31511
+ const canUseProvider = this.canUseProvider;
31512
+ return {
31513
+ autoModels: this.autoModels,
31514
+ canUseProvider: canUseProvider ? (providerId) => canUseProvider(providerId, { requestContext }) : void 0
31515
+ };
31516
+ }
31470
31517
  async resolveAutoModel(options) {
31471
31518
  let mainModel = options?.currentModel?.model;
31472
31519
  if (!mainModel && options?.mainAgent) mainModel = await options.mainAgent.getModel({ requestContext: options.requestContext });
31473
31520
  const mainModelId = getModelId(mainModel);
31474
- const pick = resolveAutoModelId(mainModelId, { autoModels: this.autoModels }) ?? (mainModel ? void 0 : OBSERVATIONAL_MEMORY_DEFAULTS.observation.model);
31521
+ const pick = resolveAutoModelId(mainModelId, this.autoModelOptions(options?.requestContext)) ?? (mainModel ? void 0 : OBSERVATIONAL_MEMORY_DEFAULTS.observation.model);
31475
31522
  if (mainModel && (!pick || pick === mainModelId)) return mainModel;
31476
31523
  const modelId = pick;
31477
31524
  return this.resolveAutoModelHook ? await this.resolveAutoModelHook(modelId, { requestContext: options?.requestContext }) : modelId;
@@ -31538,7 +31585,7 @@ var ObservationalMemory = class ObservationalMemory {
31538
31585
  async getCompressionStartLevel(requestContext) {
31539
31586
  try {
31540
31587
  const reflectionModel = await this.resolveModelFunction(this.reflectionConfig.model, requestContext);
31541
- if ((reflectionModel === "auto" ? resolveAutoModelId(void 0, { autoModels: this.autoModels }) ?? "" : (await this.resolveModelContext(reflectionModel, requestContext))?.modelId ?? "").includes("gemini-2.5-flash")) return 2;
31588
+ if ((reflectionModel === "auto" ? resolveAutoModelId(void 0, this.autoModelOptions(requestContext)) ?? "" : (await this.resolveModelContext(reflectionModel, requestContext))?.modelId ?? "").includes("gemini-2.5-flash")) return 2;
31542
31589
  return 1;
31543
31590
  } catch {
31544
31591
  return 1;
@@ -35525,6 +35572,7 @@ ${workingMemory}`;
35525
35572
  shareTokenBudget: omConfig.shareTokenBudget,
35526
35573
  model: omConfig.model,
35527
35574
  autoModels: omConfig.autoModels,
35575
+ canUseProvider: omConfig.canUseProvider,
35528
35576
  resolveModel: omConfig.resolveModel,
35529
35577
  mastra: this._mastraInstance,
35530
35578
  onIndexObservations,
@@ -36680,4 +36728,4 @@ Notes:
36680
36728
  //#endregion
36681
36729
  export { renderSubconsciousActivity as $, buildObserverSystemPrompt as A, OBSERVATION_CONTEXT_INSTRUCTIONS as B, WorkingMemoryExtractor as C, TokenCounter as D, summarizeConversation as E, parseObserverOutput as F, Subconscious as G, OBSERVATION_CONTEXT_PROMPT_THREAD as H, injectAnchorIds as I, SubconsciousRemindExtractor as J, KnowledgeSemanticIndexCoordinator as K, parseAnchorId as L, formatMessagesForObserver as M, hasCurrentTaskSection as N, OBSERVER_SYSTEM_PROMPT as O, optimizeObservationsForContext as P, publishSubconsciousActivity as Q, stripEphemeralAnchorIds as R, wrapInObservationGroup as S, SUMMARIZE_THREAD_DEFAULTS as T, OBSERVATION_CONTINUATION_HINT as U, OBSERVATION_CONTEXT_PROMPT as V, getObservationContextPrompt as W, SUBCONSCIOUS_ACTIVITY_STATE_ID as X, ModelByInputTokens as Y, buildSubconsciousActivitySnapshot as Z, deriveObservationGroupProvenance as _, extractWorkingMemoryContent as a, renderObservationGroupsForReflection as b, getObservationsAsOf as c, AUTO_MODEL_BY_PROVIDER as d, Extractor as et, resolveAutoModelId as f, combineObservationGroupRanges as g, WorkingMemoryStateProcessor as h, WorkingMemory as i, extractCurrentTask as j, buildObserverPrompt 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, StaleKnowledgeSemanticIndexError as q, SemanticRecall as r, removeWorkingMemoryTags as s, Memory as t, ObservationalMemory as u, parseObservationGroups as v, deepMergeWorkingMemory as w, stripObservationGroups as x, reconcileObservationGroupsFromReflection as y, OBSERVATIONAL_MEMORY_DEFAULTS as z };
36682
36730
 
36683
- //# sourceMappingURL=src-CnLuefUv.js.map
36731
+ //# sourceMappingURL=src-D9Uu93Xu.js.map