@mastra/memory 1.41.3-alpha.4 → 1.41.3

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.
@@ -25050,6 +25050,17 @@ function isTransientLLMError(error) {
25050
25050
  return visit(error);
25051
25051
  }
25052
25052
  /**
25053
+ * Returns true when the error says the provider account has no credits or quota left, as core's
25054
+ * provider-error classifier decides it. These can carry a retryable status (OpenAI's are HTTP 429,
25055
+ * the status of a rate limit), so `withRetry` stops on them even though `isTransientLLMError`
25056
+ * matches: the account stays unusable until someone adds credits. Rate limits are still retried.
25057
+ *
25058
+ * @internal
25059
+ */
25060
+ function isExhaustedAccountError(error) {
25061
+ return (0, _mastra_core_error.classifyProviderError)(error) === "quota";
25062
+ }
25063
+ /**
25053
25064
  * Compute the backoff delay (ms) for the Nth retry (0-indexed).
25054
25065
  *
25055
25066
  * Exponential growth (`initialDelayMs * backoffFactor^attempt`) capped at
@@ -25133,7 +25144,8 @@ async function attemptWithIdleTimeout(fn, label, idleTimeoutMs, abortSignal) {
25133
25144
  /**
25134
25145
  * Run `fn` with retries on transient transport-class errors.
25135
25146
  *
25136
- * Non-transient errors (auth, validation, schema, etc.) are rethrown
25147
+ * Non-transient errors (auth, validation, schema, etc.) and errors from an
25148
+ * account with no credits or quota left (see `isExhaustedAccountError`) are rethrown
25137
25149
  * immediately. User-initiated aborts are rethrown without delay.
25138
25150
  *
25139
25151
  * @internal
@@ -25149,7 +25161,7 @@ async function withRetry(fn, opts) {
25149
25161
  } catch (error) {
25150
25162
  if (abortSignal?.aborted) throw error;
25151
25163
  if (!(error instanceof OmModelCallTimeoutError) && hasAbortInChain(error)) throw error;
25152
- if (attempt >= maxRetries || !isTransientLLMError(error)) {
25164
+ if (attempt >= maxRetries || !isTransientLLMError(error) || isExhaustedAccountError(error)) {
25153
25165
  if (attempt > 0) omDebug(`[OM:retry:${label}] giving up after ${attempt} retry/retries: ${error instanceof Error ? error.message : String(error)}`);
25154
25166
  throw error;
25155
25167
  }
@@ -25951,7 +25963,7 @@ const OBSERVER_TOOL_ARGUMENT_MAX_DEPTH = 5;
25951
25963
  const OBSERVER_TOOL_ARGUMENT_MAX_ENTRIES_PER_CONTAINER = 20;
25952
25964
  const OBSERVER_TOOL_ARGUMENT_MAX_OUTLINE_ENTRIES = 100;
25953
25965
  const OBSERVER_TOOL_ARGUMENT_MAX_PATH_CHARS = 160;
25954
- function isObjectLike$1(value) {
25966
+ function isObjectLike(value) {
25955
25967
  return typeof value === "object" && value !== null;
25956
25968
  }
25957
25969
  function sanitizeSurrogates(value) {
@@ -26137,7 +26149,7 @@ function formatToolArgumentsForObserver(value, options) {
26137
26149
  maxCharacters: options?.maxCharacters ?? Number.POSITIVE_INFINITY
26138
26150
  };
26139
26151
  if (limits.maxTokens <= 0 || limits.maxCharacters <= 0) return "";
26140
- if (!isObjectLike$1(value)) {
26152
+ if (!isObjectLike(value)) {
26141
26153
  if (typeof value !== "string" || value.length <= OBSERVER_TOOL_ARGUMENT_INLINE_STRING_MAX_CHARS) {
26142
26154
  const primitive = formatPrimitive(value);
26143
26155
  return fits(primitive, limits) ? primitive : fits("\u2026", limits) ? "\u2026" : "";
@@ -26216,7 +26228,7 @@ function formatToolArgumentsForObserver(value, options) {
26216
26228
  });
26217
26229
  continue;
26218
26230
  }
26219
- if (!isObjectLike$1(entryValue)) {
26231
+ if (!isObjectLike(entryValue)) {
26220
26232
  outline.push({
26221
26233
  text: `${path}: ${formatPrimitive(entryValue)}`,
26222
26234
  depth: current.depth,
@@ -26298,28 +26310,22 @@ function formatToolArgumentsForObserver(value, options) {
26298
26310
  // src/processors/observational-memory/tool-result-helpers.ts
26299
26311
  const ENCRYPTED_CONTENT_KEY = "encryptedContent";
26300
26312
  const ENCRYPTED_CONTENT_REDACTION_THRESHOLD = 256;
26301
- function isObjectLike(value) {
26302
- return typeof value === "object" && value !== null;
26303
- }
26304
- function sanitizeToolResultValue(value, seen = /* @__PURE__ */ new WeakMap()) {
26305
- if (!isObjectLike(value)) return value;
26306
- if (seen.has(value)) return seen.get(value);
26307
- if (Array.isArray(value)) {
26308
- const sanitizedArray = [];
26309
- seen.set(value, sanitizedArray);
26310
- for (const item of value) sanitizedArray.push(sanitizeToolResultValue(item, seen));
26311
- return sanitizedArray;
26312
- }
26313
- const sanitizedObject = {};
26314
- seen.set(value, sanitizedObject);
26315
- for (const [key, entry] of Object.entries(value)) {
26316
- if (key === ENCRYPTED_CONTENT_KEY && typeof entry === "string" && entry.length > ENCRYPTED_CONTENT_REDACTION_THRESHOLD) {
26317
- sanitizedObject[key] = `[stripped encryptedContent: ${entry.length} characters]`;
26318
- continue;
26319
- }
26320
- sanitizedObject[key] = sanitizeToolResultValue(entry, seen);
26313
+ /** The string a boxed `String` serializes to; JSON.stringify unboxes it only after the replacer has run. */
26314
+ function unboxedString(value) {
26315
+ if (typeof value === "string") return value;
26316
+ if (typeof value !== "object" || value === null) return void 0;
26317
+ try {
26318
+ String.prototype.valueOf.call(value);
26319
+ } catch {
26320
+ return;
26321
26321
  }
26322
- return sanitizedObject;
26322
+ return String(value);
26323
+ }
26324
+ /** Redacts long `encryptedContent` strings: opaque provider data that would otherwise dominate the count. */
26325
+ function redactEncryptedContent(key, value) {
26326
+ if (key !== ENCRYPTED_CONTENT_KEY) return value;
26327
+ const text = unboxedString(value);
26328
+ return text !== void 0 && text.length > ENCRYPTED_CONTENT_REDACTION_THRESHOLD ? `[stripped encryptedContent: ${text.length} characters]` : value;
26323
26329
  }
26324
26330
  /**
26325
26331
  * Serializes a tool result without truncating it.
@@ -26339,14 +26345,20 @@ function serializeToolResultForTokenCounting(value) {
26339
26345
  function toolErrorTextToString(errorText) {
26340
26346
  return errorText == null ? "" : stringifyToolResult(errorText);
26341
26347
  }
26348
+ /**
26349
+ * Serializes with `JSON.stringify` itself, the serializer storage uses, so a count of this text describes what
26350
+ * storage holds and a reload reads back (`toJSON()`, boxed primitives, class instances, array indices).
26351
+ */
26342
26352
  function stringifyToolResult(value) {
26343
26353
  if (typeof value === "string") return value;
26344
- const sanitized = sanitizeToolResultValue(value);
26354
+ let json;
26345
26355
  try {
26346
- return JSON.stringify(sanitized, null, 2);
26356
+ json = JSON.stringify(value, redactEncryptedContent, 2);
26347
26357
  } catch {
26348
- return String(sanitized);
26358
+ return String(value);
26349
26359
  }
26360
+ if (json === void 0) return "";
26361
+ return json.startsWith("\"") ? JSON.parse(json) : json;
26350
26362
  }
26351
26363
  function resolveToolResultValue(part, invocationResult) {
26352
26364
  const mastraMetadata = part?.providerMetadata?.mastra;
@@ -26360,13 +26372,58 @@ function resolveToolResultValue(part, invocationResult) {
26360
26372
  usingStoredModelOutput: false
26361
26373
  };
26362
26374
  }
26375
+ const PREFIX_CHUNK_MIN_LENGTH = 256;
26376
+ function isAsciiAlphanumeric(code) {
26377
+ return code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122;
26378
+ }
26379
+ function isSplitWhitespace(code) {
26380
+ return code === 32 || code === 10 || code === 9 || code === 13;
26381
+ }
26382
+ /**
26383
+ * Returns a function that counts `estimateTokenCount(text.slice(0, end) + suffix)` without rescanning the
26384
+ * whole prefix on every call.
26385
+ *
26386
+ * tokenx splits text into segments on whitespace and punctuation runs and sums a per-segment estimate.
26387
+ * Letters and digits are never separators and whitespace always is, so the position between an ASCII
26388
+ * letter or digit and a following whitespace character is always a segment boundary: the count of any
26389
+ * string that shares the text up to such a position equals the count before it plus the count after it.
26390
+ * The text is cut at those boundaries once, and each call only rescans the chunk it ends in.
26391
+ */
26392
+ function createPrefixTokenCounter(text) {
26393
+ const boundaries = [0];
26394
+ const tokensBefore = [0];
26395
+ let chunkStart = 0;
26396
+ let runningTokens = 0;
26397
+ for (let i = PREFIX_CHUNK_MIN_LENGTH; i < text.length; i++) if (i - chunkStart >= PREFIX_CHUNK_MIN_LENGTH && isSplitWhitespace(text.charCodeAt(i)) && isAsciiAlphanumeric(text.charCodeAt(i - 1))) {
26398
+ runningTokens += estimateTokenCount(text.slice(chunkStart, i));
26399
+ boundaries.push(i);
26400
+ tokensBefore.push(runningTokens);
26401
+ chunkStart = i;
26402
+ }
26403
+ return (end, suffix = "") => {
26404
+ let low = 0;
26405
+ let high = boundaries.length - 1;
26406
+ while (low < high) {
26407
+ const mid = low + high + 1 >> 1;
26408
+ if (boundaries[mid] <= end) low = mid;
26409
+ else high = mid - 1;
26410
+ }
26411
+ return tokensBefore[low] + estimateTokenCount(text.slice(boundaries[low], end) + suffix);
26412
+ };
26413
+ }
26363
26414
  function truncateStringByTokens(text, maxTokens) {
26364
26415
  if (!text || maxTokens <= 0) return "";
26365
- const totalTokens = estimateTokenCount(text);
26416
+ const countPrefixTokens = createPrefixTokenCounter(text);
26417
+ const totalTokens = countPrefixTokens(text.length);
26366
26418
  if (totalTokens <= maxTokens) return text;
26367
26419
  const buildCandidate = (sliceEnd) => {
26368
- const visible = safeSlice(text, sliceEnd);
26369
- return `${visible}\n... [truncated ~${totalTokens - estimateTokenCount(visible)} tokens]`;
26420
+ const visibleEnd = safeSlice(text, sliceEnd).length;
26421
+ const suffix = `\n... [truncated ~${totalTokens - countPrefixTokens(visibleEnd)} tokens]`;
26422
+ return {
26423
+ visibleEnd,
26424
+ suffix,
26425
+ tokens: countPrefixTokens(visibleEnd, suffix)
26426
+ };
26370
26427
  };
26371
26428
  let low = 0;
26372
26429
  let high = text.length;
@@ -26374,12 +26431,12 @@ function truncateStringByTokens(text, maxTokens) {
26374
26431
  while (low <= high) {
26375
26432
  const mid = Math.floor((low + high) / 2);
26376
26433
  const candidate = buildCandidate(mid);
26377
- if (estimateTokenCount(candidate) <= maxTokens) {
26434
+ if (candidate.tokens <= maxTokens) {
26378
26435
  best = candidate;
26379
26436
  low = mid + 1;
26380
26437
  } else high = mid - 1;
26381
26438
  }
26382
- return best;
26439
+ return text.slice(0, best.visibleEnd) + best.suffix;
26383
26440
  }
26384
26441
  function formatToolResultForObserver(value, options) {
26385
26442
  return truncateStringByTokens(stringifyToolResult(value), options?.maxTokens ?? 5e3);
@@ -28645,9 +28702,24 @@ function mergeCacheEntry(cache, key, entry) {
28645
28702
  function getPartCacheEntry(part, key) {
28646
28703
  return getCacheEntry(getPartMastraMetadata(part)?.tokenEstimate, key);
28647
28704
  }
28705
+ /**
28706
+ * Parts this process gave a new stored count. A part loaded from storage with its count is never in here,
28707
+ * so a message holding one of these parts has a count storage does not have yet.
28708
+ */
28709
+ const partsWithUnsavedCount = /* @__PURE__ */ new WeakSet();
28710
+ /** Whether `part` gained a stored count in this process that has not been handed to a save yet. */
28711
+ function hasUnsavedTokenEstimate(part) {
28712
+ return typeof part === "object" && part !== null && partsWithUnsavedCount.has(part);
28713
+ }
28714
+ /** Note that `part`'s count is on its way to storage, so later steps do not save it again. */
28715
+ function markTokenEstimateSaved(part) {
28716
+ if (typeof part === "object" && part !== null) partsWithUnsavedCount.delete(part);
28717
+ }
28718
+ const partCountMemo = /* @__PURE__ */ new WeakMap();
28648
28719
  function setPartCacheEntry(part, key, entry) {
28649
28720
  const mastraMetadata = ensurePartMastraMetadata(part);
28650
28721
  mastraMetadata.tokenEstimate = mergeCacheEntry(mastraMetadata.tokenEstimate, key, entry);
28722
+ partsWithUnsavedCount.add(part);
28651
28723
  }
28652
28724
  /**
28653
28725
  * Extracts a caller-supplied token estimate stamped on a part via
@@ -29341,14 +29413,19 @@ async function fetchGoogleAttachmentTokenEstimate(modelId, part) {
29341
29413
  * undercounted as generic JSON blobs.
29342
29414
  */
29343
29415
  var TokenCounter = class TokenCounter {
29344
- cacheSource;
29416
+ /**
29417
+ * Stored counts belong to the stock estimator. A subclass or instance that overrides `countString`
29418
+ * reads and writes its own namespace, so it never reuses a count the stock estimator saved.
29419
+ */
29420
+ get cacheSource() {
29421
+ return this.countString === TokenCounter.prototype.countString ? `v${TOKEN_ESTIMATE_CACHE_VERSION}:${resolveEstimatorId()}` : `v${TOKEN_ESTIMATE_CACHE_VERSION}:custom`;
29422
+ }
29345
29423
  defaultModelContext;
29346
29424
  inFlightAttachmentCounts = /* @__PURE__ */ new Map();
29347
29425
  multimodalToolResultCounts = /* @__PURE__ */ new WeakMap();
29348
29426
  static TOKENS_PER_MESSAGE = 3.8;
29349
29427
  static TOKENS_PER_CONVERSATION = 24;
29350
29428
  constructor(options) {
29351
- this.cacheSource = `v${TOKEN_ESTIMATE_CACHE_VERSION}:${resolveEstimatorId()}`;
29352
29429
  this.defaultModelContext = parseModelContext(options?.model);
29353
29430
  }
29354
29431
  runWithModelContext(model, fn) {
@@ -29379,6 +29456,28 @@ var TokenCounter = class TokenCounter {
29379
29456
  });
29380
29457
  return tokens;
29381
29458
  }
29459
+ /**
29460
+ * Count one content-only piece of a part (its text, a tool's args or result) the same way as
29461
+ * {@link readOrPersistPartEstimate}: a stored count is reused only when its content hash matches.
29462
+ * `refs` are the values the payload is built from. While the same part object still holds the same
29463
+ * refs, the count from the last call is returned without serializing or hashing again, so a part
29464
+ * counted by `getStatus` and then by the next step is hashed once per process.
29465
+ * Only string refs are memoized (object payloads are hashed every time, since they can change in place).
29466
+ */
29467
+ readOrPersistMemoizedPartEstimate(part, kind, refs, getPayload) {
29468
+ if (!refs.every((ref) => typeof ref === "string")) return this.readOrPersistPartEstimate(part, kind, getPayload());
29469
+ let byKind = partCountMemo.get(part);
29470
+ const memo = byKind?.get(kind);
29471
+ if (memo && memo.owner === this && memo.refs.length === refs.length && memo.refs.every((ref, i) => ref === refs[i])) return memo.tokens;
29472
+ const tokens = this.readOrPersistPartEstimate(part, kind, getPayload());
29473
+ if (!byKind) partCountMemo.set(part, byKind = /* @__PURE__ */ new Map());
29474
+ byKind.set(kind, {
29475
+ owner: this,
29476
+ refs,
29477
+ tokens
29478
+ });
29479
+ return tokens;
29480
+ }
29382
29481
  readOrPersistFixedPartEstimate(part, kind, payload, tokens) {
29383
29482
  const key = buildEstimateKey(kind, payload);
29384
29483
  const cached = getPartCacheEntry(part, key);
@@ -29729,18 +29828,23 @@ var TokenCounter = class TokenCounter {
29729
29828
  /**
29730
29829
  * Count the name and the arguments of a tool call. Every state before the tool produces an
29731
29830
  * output holds the same call signature in the context window, so all of those states share
29732
- * these cache kinds. `buildEstimateKey` hashes the text, so a shared kind stays correct and
29733
- * keeps the estimate warm while the invocation moves from one state to the next.
29831
+ * these cache kinds, and the estimate stays warm while the invocation moves from one state to
29832
+ * the next. Name and args don't change across those states once the call stops streaming.
29734
29833
  */
29735
29834
  countToolCallSignature(part, invocation) {
29736
29835
  let tokens = 0;
29737
29836
  let overheadDelta = 0;
29738
- if (invocation.toolName) tokens += this.readOrPersistPartEstimate(part, "tool-call-name", invocation.toolName);
29837
+ const storable = invocation.state !== "partial-call";
29838
+ const count = (kind, ref, getPayload) => storable ? this.readOrPersistMemoizedPartEstimate(part, kind, [ref], getPayload) : this.readOrPersistPartEstimate(part, kind, getPayload());
29839
+ if (invocation.toolName) {
29840
+ const toolName = invocation.toolName;
29841
+ tokens += count("tool-call-name", toolName, () => toolName);
29842
+ }
29739
29843
  if (invocation.args !== void 0) {
29740
- if (typeof invocation.args === "string") tokens += this.readOrPersistPartEstimate(part, "tool-call-args", invocation.args);
29844
+ const args = invocation.args;
29845
+ if (typeof args === "string") tokens += count("tool-call-args", args, () => args);
29741
29846
  else {
29742
- const argsJson = JSON.stringify(invocation.args);
29743
- tokens += this.readOrPersistPartEstimate(part, "tool-call-args-json", argsJson);
29847
+ tokens += count("tool-call-args-json", args, () => JSON.stringify(args));
29744
29848
  overheadDelta -= 12;
29745
29849
  }
29746
29850
  }
@@ -29752,11 +29856,14 @@ var TokenCounter = class TokenCounter {
29752
29856
  countNonAttachmentPart(part) {
29753
29857
  let overheadDelta = 0;
29754
29858
  let extraMessageDelta = 0;
29755
- if (part.type === "text") return {
29756
- tokens: this.readOrPersistPartEstimate(part, "text", part.text),
29757
- overheadDelta,
29758
- extraMessageDelta
29759
- };
29859
+ if (part.type === "text") {
29860
+ const text = part.text;
29861
+ return {
29862
+ tokens: this.readOrPersistMemoizedPartEstimate(part, "text", [text], () => text),
29863
+ overheadDelta,
29864
+ extraMessageDelta
29865
+ };
29866
+ }
29760
29867
  if (part.type === "tool-invocation") {
29761
29868
  const invocation = part.toolInvocation;
29762
29869
  const state = invocation.state;
@@ -29775,7 +29882,7 @@ var TokenCounter = class TokenCounter {
29775
29882
  tokens += signature.tokens;
29776
29883
  overheadDelta += signature.overheadDelta;
29777
29884
  const reason = invocation.approval?.reason;
29778
- if (reason) tokens += this.readOrPersistPartEstimate(part, "tool-approval-reason", reason);
29885
+ if (reason) tokens += this.readOrPersistMemoizedPartEstimate(part, "tool-approval-reason", [reason], () => reason);
29779
29886
  return {
29780
29887
  tokens,
29781
29888
  overheadDelta,
@@ -29791,15 +29898,12 @@ var TokenCounter = class TokenCounter {
29791
29898
  if (resultForCounting !== void 0 && (typeof resultForCounting !== "string" || resultForCounting.trim().length > 0)) {
29792
29899
  const contentTokens = this.countMultimodalToolResultContent(part, resultForCounting);
29793
29900
  if (contentTokens !== void 0) tokens += contentTokens;
29794
- else {
29795
- const formattedResult = serializeToolResultForTokenCounting(resultForCounting);
29796
- tokens += this.readOrPersistPartEstimate(part, usingStoredModelOutput ? "tool-result-model-output-json" : "tool-result-json", formattedResult);
29797
- }
29901
+ else tokens += this.readOrPersistMemoizedPartEstimate(part, usingStoredModelOutput ? "tool-result-model-output-json" : "tool-result-json", [resultForCounting], () => serializeToolResultForTokenCounting(resultForCounting));
29798
29902
  if (typeof resultForCounting !== "string") overheadDelta -= 12;
29799
29903
  } else {
29800
29904
  const errorText = toolErrorTextToString(invocation.errorText);
29801
29905
  const fallback = invocation.isError ? errorText.trim() ? errorText : "Tool execution failed" : "[empty result]";
29802
- tokens += this.readOrPersistPartEstimate(part, invocation.isError ? "tool-result-error" : "tool-result-json", fallback);
29906
+ tokens += this.readOrPersistMemoizedPartEstimate(part, invocation.isError ? "tool-result-error" : "tool-result-json", [fallback], () => fallback);
29803
29907
  }
29804
29908
  return {
29805
29909
  tokens,
@@ -29813,7 +29917,7 @@ var TokenCounter = class TokenCounter {
29813
29917
  tokens += signature.tokens;
29814
29918
  overheadDelta += signature.overheadDelta;
29815
29919
  const reason = invocation.approval?.reason?.trim() ? invocation.approval.reason : "Tool call was not approved by the user";
29816
- tokens += this.readOrPersistPartEstimate(part, "tool-result-denied", reason);
29920
+ tokens += this.readOrPersistMemoizedPartEstimate(part, "tool-result-denied", [reason], () => reason);
29817
29921
  return {
29818
29922
  tokens,
29819
29923
  overheadDelta,
@@ -29827,7 +29931,7 @@ var TokenCounter = class TokenCounter {
29827
29931
  overheadDelta += signature.overheadDelta;
29828
29932
  const errorText = toolErrorTextToString(invocation.errorText);
29829
29933
  const errorMessage = errorText.trim() ? errorText : "Tool execution failed";
29830
- tokens += this.readOrPersistPartEstimate(part, "tool-result-error", errorMessage);
29934
+ tokens += this.readOrPersistMemoizedPartEstimate(part, "tool-result-error", [errorMessage], () => errorMessage);
29831
29935
  return {
29832
29936
  tokens,
29833
29937
  overheadDelta,
@@ -29840,6 +29944,11 @@ var TokenCounter = class TokenCounter {
29840
29944
  overheadDelta,
29841
29945
  extraMessageDelta
29842
29946
  };
29947
+ if (part.type === "step-start") return {
29948
+ tokens: 0,
29949
+ overheadDelta,
29950
+ extraMessageDelta
29951
+ };
29843
29952
  if (part.type === "reasoning") return {
29844
29953
  tokens: 0,
29845
29954
  overheadDelta,
@@ -33251,6 +33360,7 @@ const threadTitleInstructions = `A short, noun-phrase title for this conversatio
33251
33360
  - "Auth bug fix" \u2014 not "Fixing the auth bug"
33252
33361
  - "Dark mode toggle" \u2014 not "User wants dark mode toggle added"
33253
33362
  - "Deployment pipeline setup" \u2014 not "Setting up deployment pipeline for project"
33363
+ Write the title in the same language the user's messages are written in.
33254
33364
  Only update when the topic meaningfully changes.`;
33255
33365
  function createCurrentTaskExtractor() {
33256
33366
  return new Extractor({
@@ -35212,6 +35322,47 @@ ObservationStrategy.create = ((om, opts) => {
35212
35322
  if (deps.scope === "resource" && opts.resourceId) return new ResourceScopedObservationStrategy(deps, opts);
35213
35323
  return new SyncObservationStrategy(deps, opts);
35214
35324
  });
35325
+ // src/processors/observational-memory/resave-counted-messages.ts
35326
+ /**
35327
+ * Mark the stored history of `threadId` in `messageList` that OM gave new token counts, so the counts are saved
35328
+ * with the messages. Call the returned function once the counting is done: every message holding a part that
35329
+ * gained a count in this process is marked for resave, and the normal save writes it back whole. Counts made
35330
+ * before this is called (while the turn loaded history) are caught too.
35331
+ *
35332
+ * Only messages of `threadId` are marked. A message recalled from another thread of the resource is counted but
35333
+ * never written, because saving it would bump that thread's `updatedAt` and reorder the recent-thread list.
35334
+ *
35335
+ * A Core without `markForResave` is left alone: counting still works, the counts are just not saved.
35336
+ */
35337
+ function resaveCountedMessagesFor(messageList, threadId) {
35338
+ if (typeof messageList.markForResave !== "function") return () => {};
35339
+ return () => {
35340
+ for (const message of messageList.get.remembered.db()) {
35341
+ if (message.threadId !== threadId) continue;
35342
+ const parts = message.content?.parts ?? [];
35343
+ if (!parts.some(hasUnsavedTokenEstimate)) continue;
35344
+ messageList.markForResave(message);
35345
+ parts.forEach(markTokenEstimateSaved);
35346
+ }
35347
+ };
35348
+ }
35349
+ /** The stored messages marked for resave in `messageList`; none for a Core without `markForResave`. */
35350
+ function messagesMarkedForResave(messageList) {
35351
+ return typeof messageList.getMessagesToResave === "function" ? messageList.getMessagesToResave() : [];
35352
+ }
35353
+ /**
35354
+ * Ids of the stored messages marked for resave in `messageList` that are not in `ownMessages` (the turn's
35355
+ * own input and output). Those are saved whole; the rest only gained counts and are patched onto storage.
35356
+ */
35357
+ function idsMarkedForResave(messageList, ownMessages = []) {
35358
+ const own = new Set(ownMessages.map((message) => message.id));
35359
+ return new Set(messagesMarkedForResave(messageList).map((message) => message.id).filter((id) => !own.has(id)));
35360
+ }
35361
+ /** `messages` with the messages marked for resave added, each message once. */
35362
+ function withMessagesMarkedForResave(messageList, messages) {
35363
+ const ids = new Set(messages.map((message) => message.id));
35364
+ return [...messages, ...messagesMarkedForResave(messageList).filter((message) => !ids.has(message.id))];
35365
+ }
35215
35366
  // src/processors/observational-memory/observation-turn/load-memory-context.ts
35216
35367
  async function loadMemoryContextMessages({ memory, messageList, threadId, resourceId, runState }) {
35217
35368
  const ctx = await memory.getContext({
@@ -35219,7 +35370,8 @@ async function loadMemoryContextMessages({ memory, messageList, threadId, resour
35219
35370
  resourceId,
35220
35371
  runState
35221
35372
  });
35222
- for (const msg of ctx.messages) if (msg.role !== "system") messageList.add(msg, "memory");
35373
+ const messages = ctx.messages.filter((msg) => msg.role !== "system");
35374
+ if (messages.length) messageList.add(messages, "memory");
35223
35375
  return ctx;
35224
35376
  }
35225
35377
  // src/processors/observational-memory/observation-turn/safe-buffer-prefix.ts
@@ -35426,7 +35578,7 @@ var ObservationStep = class {
35426
35578
  const inputIds = new Set(messageList.get.input.db().map((msg) => msg.id));
35427
35579
  const sealedOutput = safeCandidates.filter((msg) => !inputIds.has(msg.id));
35428
35580
  messageList.removeByIds(sealedOutput.map((msg) => msg.id));
35429
- for (const msg of sealedOutput) messageList.add(msg, "memory");
35581
+ if (sealedOutput.length) messageList.add(sealedOutput, "memory");
35430
35582
  }
35431
35583
  if (!deferred) {
35432
35584
  om.trackBackgroundWork(om.buffer({
@@ -35475,7 +35627,7 @@ var ObservationStep = class {
35475
35627
  }).map((msg) => msg.id);
35476
35628
  inFlightIds = [...new Set(unreadIds)];
35477
35629
  if (messagesToSave.length > 0) {
35478
- for (const msg of messagesToSave) messageList.add(msg, "memory");
35630
+ messageList.add(messagesToSave, "memory");
35479
35631
  try {
35480
35632
  await om.persistMessages(messagesToSave, threadId, resourceId);
35481
35633
  } catch (error) {
@@ -35978,8 +36130,8 @@ var ObservationTurn = class {
35978
36130
  this._ended = true;
35979
36131
  const unsavedInput = messageList.get.input.db();
35980
36132
  const unsavedOutput = messageList.get.response.db();
35981
- const unsavedMessages = [...unsavedInput, ...unsavedOutput];
35982
- if (unsavedMessages.length > 0) await this.om.persistMessages(unsavedMessages, this.threadId, this.resourceId);
36133
+ const unsavedMessages = withMessagesMarkedForResave(messageList, [...unsavedInput, ...unsavedOutput]);
36134
+ if (unsavedMessages.length > 0) await this.om.persistMessages(unsavedMessages, this.threadId, this.resourceId, idsMarkedForResave(messageList, [...unsavedInput, ...unsavedOutput]));
35983
36135
  const asyncObservationEnabled = this.om.buffering.isAsyncObservationEnabled();
35984
36136
  const bufferOnIdle = this.om.getObservationConfig().bufferOnIdle;
35985
36137
  if (!this.abortSignal?.aborted && asyncObservationEnabled && bufferOnIdle) {
@@ -38888,18 +39040,86 @@ var ObservationalMemory = class ObservationalMemory {
38888
39040
  * to detect already-persisted messages, avoiding redundant DB operations.
38889
39041
  *
38890
39042
  * Messages with observation markers are always saved (upserted) even if sealed,
38891
- * because the markers need to be persisted to storage.
39043
+ * because the markers need to be persisted to storage. A stored message in `resaveIds` gained token
39044
+ * counts after it was stored, whether or not it is sealed: only those counts are copied onto the stored
39045
+ * copy, see {@link persistTokenEstimatesOntoStored}; one with no stored row was deleted during the turn and stays deleted. Ids in `resaveIds` must not be this turn's own
39046
+ * input or output, which are saved whole.
38892
39047
  */
38893
- async persistMessages(messagesToSave, threadId, resourceId) {
39048
+ async persistMessages(messagesToSave, threadId, resourceId, resaveIds) {
38894
39049
  const filteredMessages = [];
38895
- for (const msg of messagesToSave) if (!!(msg.content?.metadata)?.mastra?.sealed) {
38896
- if (findLastCompletedObservationBoundary(msg) !== -1) filteredMessages.push(msg);
38897
- } else filteredMessages.push(msg);
39050
+ const storedWithNewCounts = [];
39051
+ for (const msg of messagesToSave) {
39052
+ if (!!(msg.content?.metadata)?.mastra?.sealed && findLastCompletedObservationBoundary(msg) === -1 && !resaveIds?.has(msg.id)) continue;
39053
+ if (resaveIds?.has(msg.id) && findLastCompletedObservationBoundary(msg) === -1) storedWithNewCounts.push(msg);
39054
+ else filteredMessages.push(msg);
39055
+ }
38898
39056
  if (filteredMessages.length > 0) await this.messageHistory.persistMessages({
38899
39057
  messages: filteredMessages,
38900
39058
  threadId,
38901
39059
  resourceId
38902
39060
  });
39061
+ try {
39062
+ await this.persistTokenEstimatesOntoStored(storedWithNewCounts);
39063
+ } catch (error) {
39064
+ omError("[OM] Failed to save token counts for stored messages", error);
39065
+ }
39066
+ }
39067
+ /**
39068
+ * Copy the token counts of `messages` onto their stored copies. A stored copy can hold
39069
+ * parts the in-memory one lacks (markers written straight to storage), so it is patched
39070
+ * instead of saved whole. Each count goes to the first stored part whose content matches the counted
39071
+ * part, so a part that changed in storage keeps no count and is counted again on read.
39072
+ */
39073
+ async persistTokenEstimatesOntoStored(messages) {
39074
+ if (messages.length === 0) return;
39075
+ const contentOf = (part) => {
39076
+ const { tokenEstimate: _tokenEstimate, ...mastra } = part.providerMetadata?.mastra ?? {};
39077
+ return JSON.stringify({
39078
+ ...part,
39079
+ providerMetadata: {
39080
+ ...part.providerMetadata,
39081
+ mastra
39082
+ }
39083
+ });
39084
+ };
39085
+ const live = new Map(messages.map((message) => [message.id, message]));
39086
+ const { messages: stored } = await this.storage.listMessagesById({ messageIds: [...live.keys()] });
39087
+ const updates = [];
39088
+ for (const row of stored) {
39089
+ const counts = /* @__PURE__ */ new Map();
39090
+ for (const part of live.get(row.id)?.content.parts ?? []) {
39091
+ const tokenEstimate = part.providerMetadata?.mastra?.tokenEstimate;
39092
+ if (!tokenEstimate) continue;
39093
+ const key = contentOf(part);
39094
+ counts.set(key, [...counts.get(key) ?? [], tokenEstimate]);
39095
+ }
39096
+ if (counts.size === 0) continue;
39097
+ let changed = false;
39098
+ const parts = row.content.parts.map((part) => {
39099
+ const tokenEstimate = counts.get(contentOf(part))?.shift();
39100
+ if (!tokenEstimate) return part;
39101
+ changed = true;
39102
+ const providerMetadata = part.providerMetadata ?? {};
39103
+ return {
39104
+ ...part,
39105
+ providerMetadata: {
39106
+ ...providerMetadata,
39107
+ mastra: {
39108
+ ...providerMetadata.mastra,
39109
+ tokenEstimate
39110
+ }
39111
+ }
39112
+ };
39113
+ });
39114
+ if (changed) updates.push({
39115
+ id: row.id,
39116
+ content: {
39117
+ ...row.content,
39118
+ parts
39119
+ }
39120
+ });
39121
+ }
39122
+ if (updates.length > 0) await this.storage.updateMessages({ messages: updates });
38903
39123
  }
38904
39124
  /**
38905
39125
  * Load messages from storage that haven't been observed yet.
@@ -40702,11 +40922,12 @@ var ObservationalMemoryProcessor = class {
40702
40922
  state.__omTurn = void 0;
40703
40923
  if (!activeTurn || activeTurn.ended) return;
40704
40924
  const terminalList = messageList ?? activeTurn.messageList;
40705
- const unsavedMessages = [...terminalList.get.input.db(), ...terminalList.get.response.db()];
40925
+ const ownMessages = [...terminalList.get.input.db(), ...terminalList.get.response.db()];
40926
+ const unsavedMessages = withMessagesMarkedForResave(terminalList, ownMessages);
40706
40927
  try {
40707
40928
  await activeTurn.end(terminalList);
40708
40929
  } catch (error) {
40709
- if (unsavedMessages.length > 0) await this.engine.persistMessages(unsavedMessages, activeTurn.threadId, activeTurn.resourceId).catch(() => {});
40930
+ if (unsavedMessages.length > 0) await this.engine.persistMessages(unsavedMessages, activeTurn.threadId, activeTurn.resourceId, idsMarkedForResave(terminalList, ownMessages)).catch(() => {});
40710
40931
  throw error;
40711
40932
  }
40712
40933
  }
@@ -40848,6 +41069,7 @@ var ObservationalMemoryProcessor = class {
40848
41069
  this.turn.responseMessageId = responseMessageId;
40849
41070
  {
40850
41071
  const step = this.turn.step(stepNumber);
41072
+ const resaveCounted = resaveCountedMessagesFor(messageList, threadId);
40851
41073
  let ctx;
40852
41074
  try {
40853
41075
  ctx = await step.prepare();
@@ -40882,6 +41104,7 @@ var ObservationalMemoryProcessor = class {
40882
41104
  threadId,
40883
41105
  resourceId
40884
41106
  });
41107
+ resaveCounted();
40885
41108
  const finalTotalPending = ctx.status.pendingTokens;
40886
41109
  try {
40887
41110
  await runOMCommit(this.engine.buffering.getLockKey(threadId, resourceId), () => this.engine.getStorage().setPendingMessageTokens(turnRecord.id, finalTotalPending), { abortSignal });
@@ -40921,6 +41144,7 @@ var ObservationalMemoryProcessor = class {
40921
41144
  return this.engine.getTokenCounter().runWithModelContext(state.__omActorModelContext, async () => {
40922
41145
  if ((0, _mastra_core_memory.parseMemoryRequestContext)(requestContext)?.memoryConfig?.readOnly) return messageList;
40923
41146
  const persistenceMessageList = messageList.cloneForPersistence();
41147
+ this.engine.getTokenCounter().countMessages(persistenceMessageList.get.response.db());
40924
41148
  const turn = asLiveTurn(state.__omTurn) ?? this.turn;
40925
41149
  const liveTurn = turn && !turn.ended ? turn : void 0;
40926
41150
  if (liveTurn) await liveTurn.end(persistenceMessageList);
@@ -40928,8 +41152,9 @@ var ObservationalMemoryProcessor = class {
40928
41152
  state.__omTurn = void 0;
40929
41153
  if (!liveTurn) {
40930
41154
  const newOutput = persistenceMessageList.get.response.db();
40931
- const messagesToSave = [...persistenceMessageList.get.input.db(), ...newOutput];
40932
- if (messagesToSave.length > 0 && context.threadId) await this.engine.persistMessages(messagesToSave, context.threadId, context.resourceId);
41155
+ const ownMessages = [...persistenceMessageList.get.input.db(), ...newOutput];
41156
+ const messagesToSave = withMessagesMarkedForResave(persistenceMessageList, ownMessages);
41157
+ if (messagesToSave.length > 0 && context.threadId) await this.engine.persistMessages(messagesToSave, context.threadId, context.resourceId, idsMarkedForResave(persistenceMessageList, ownMessages));
40933
41158
  }
40934
41159
  return messageList;
40935
41160
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/memory",
3
- "version": "1.41.3-alpha.4",
3
+ "version": "1.41.3",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -53,7 +53,7 @@
53
53
  "probe-image-size": "^7.4.0",
54
54
  "xxhash-wasm": "^1.1.0",
55
55
  "zod": "^4.6.7",
56
- "@mastra/schema-compat": "1.4.1-alpha.0"
56
+ "@mastra/schema-compat": "1.4.1"
57
57
  },
58
58
  "devDependencies": {
59
59
  "@ai-sdk/openai-v5": "npm:@ai-sdk/openai@2.0.139",
@@ -67,13 +67,13 @@
67
67
  "tsx": "^4.23.15",
68
68
  "typescript": "^6.0.3",
69
69
  "vitest": "5.1.0",
70
- "@internal/ai-sdk-v4": "0.0.98",
71
- "@internal/ai-sdk-v5": "0.0.98",
72
- "@internal/ai-v6": "0.0.98",
73
- "@internal/ai-v7": "0.0.98",
74
- "@internal/lint": "0.0.151",
75
- "@internal/types-builder": "0.0.126",
76
- "@mastra/core": "1.86.0-alpha.8"
70
+ "@internal/ai-sdk-v4": "0.0.99",
71
+ "@internal/ai-v7": "0.0.99",
72
+ "@internal/ai-v6": "0.0.99",
73
+ "@internal/ai-sdk-v5": "0.0.99",
74
+ "@internal/lint": "0.0.152",
75
+ "@mastra/core": "1.86.0",
76
+ "@internal/types-builder": "0.0.127"
77
77
  },
78
78
  "peerDependencies": {
79
79
  "@mastra/core": ">=1.85.1-0 <2.0.0-0"