@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.
@@ -25028,6 +25028,17 @@ function isTransientLLMError(error) {
25028
25028
  return visit(error);
25029
25029
  }
25030
25030
  /**
25031
+ * Returns true when the error says the provider account has no credits or quota left, as core's
25032
+ * provider-error classifier decides it. These can carry a retryable status (OpenAI's are HTTP 429,
25033
+ * the status of a rate limit), so `withRetry` stops on them even though `isTransientLLMError`
25034
+ * matches: the account stays unusable until someone adds credits. Rate limits are still retried.
25035
+ *
25036
+ * @internal
25037
+ */
25038
+ function isExhaustedAccountError(error) {
25039
+ return classifyProviderError(error) === "quota";
25040
+ }
25041
+ /**
25031
25042
  * Compute the backoff delay (ms) for the Nth retry (0-indexed).
25032
25043
  *
25033
25044
  * Exponential growth (`initialDelayMs * backoffFactor^attempt`) capped at
@@ -25111,7 +25122,8 @@ async function attemptWithIdleTimeout(fn, label, idleTimeoutMs, abortSignal) {
25111
25122
  /**
25112
25123
  * Run `fn` with retries on transient transport-class errors.
25113
25124
  *
25114
- * Non-transient errors (auth, validation, schema, etc.) are rethrown
25125
+ * Non-transient errors (auth, validation, schema, etc.) and errors from an
25126
+ * account with no credits or quota left (see `isExhaustedAccountError`) are rethrown
25115
25127
  * immediately. User-initiated aborts are rethrown without delay.
25116
25128
  *
25117
25129
  * @internal
@@ -25127,7 +25139,7 @@ async function withRetry(fn, opts) {
25127
25139
  } catch (error) {
25128
25140
  if (abortSignal?.aborted) throw error;
25129
25141
  if (!(error instanceof OmModelCallTimeoutError) && hasAbortInChain(error)) throw error;
25130
- if (attempt >= maxRetries || !isTransientLLMError(error)) {
25142
+ if (attempt >= maxRetries || !isTransientLLMError(error) || isExhaustedAccountError(error)) {
25131
25143
  if (attempt > 0) omDebug(`[OM:retry:${label}] giving up after ${attempt} retry/retries: ${error instanceof Error ? error.message : String(error)}`);
25132
25144
  throw error;
25133
25145
  }
@@ -25929,7 +25941,7 @@ const OBSERVER_TOOL_ARGUMENT_MAX_DEPTH = 5;
25929
25941
  const OBSERVER_TOOL_ARGUMENT_MAX_ENTRIES_PER_CONTAINER = 20;
25930
25942
  const OBSERVER_TOOL_ARGUMENT_MAX_OUTLINE_ENTRIES = 100;
25931
25943
  const OBSERVER_TOOL_ARGUMENT_MAX_PATH_CHARS = 160;
25932
- function isObjectLike$1(value) {
25944
+ function isObjectLike(value) {
25933
25945
  return typeof value === "object" && value !== null;
25934
25946
  }
25935
25947
  function sanitizeSurrogates(value) {
@@ -26115,7 +26127,7 @@ function formatToolArgumentsForObserver(value, options) {
26115
26127
  maxCharacters: options?.maxCharacters ?? Number.POSITIVE_INFINITY
26116
26128
  };
26117
26129
  if (limits.maxTokens <= 0 || limits.maxCharacters <= 0) return "";
26118
- if (!isObjectLike$1(value)) {
26130
+ if (!isObjectLike(value)) {
26119
26131
  if (typeof value !== "string" || value.length <= OBSERVER_TOOL_ARGUMENT_INLINE_STRING_MAX_CHARS) {
26120
26132
  const primitive = formatPrimitive(value);
26121
26133
  return fits(primitive, limits) ? primitive : fits("\u2026", limits) ? "\u2026" : "";
@@ -26194,7 +26206,7 @@ function formatToolArgumentsForObserver(value, options) {
26194
26206
  });
26195
26207
  continue;
26196
26208
  }
26197
- if (!isObjectLike$1(entryValue)) {
26209
+ if (!isObjectLike(entryValue)) {
26198
26210
  outline.push({
26199
26211
  text: `${path}: ${formatPrimitive(entryValue)}`,
26200
26212
  depth: current.depth,
@@ -26276,28 +26288,22 @@ function formatToolArgumentsForObserver(value, options) {
26276
26288
  // src/processors/observational-memory/tool-result-helpers.ts
26277
26289
  const ENCRYPTED_CONTENT_KEY = "encryptedContent";
26278
26290
  const ENCRYPTED_CONTENT_REDACTION_THRESHOLD = 256;
26279
- function isObjectLike(value) {
26280
- return typeof value === "object" && value !== null;
26281
- }
26282
- function sanitizeToolResultValue(value, seen = /* @__PURE__ */ new WeakMap()) {
26283
- if (!isObjectLike(value)) return value;
26284
- if (seen.has(value)) return seen.get(value);
26285
- if (Array.isArray(value)) {
26286
- const sanitizedArray = [];
26287
- seen.set(value, sanitizedArray);
26288
- for (const item of value) sanitizedArray.push(sanitizeToolResultValue(item, seen));
26289
- return sanitizedArray;
26290
- }
26291
- const sanitizedObject = {};
26292
- seen.set(value, sanitizedObject);
26293
- for (const [key, entry] of Object.entries(value)) {
26294
- if (key === ENCRYPTED_CONTENT_KEY && typeof entry === "string" && entry.length > ENCRYPTED_CONTENT_REDACTION_THRESHOLD) {
26295
- sanitizedObject[key] = `[stripped encryptedContent: ${entry.length} characters]`;
26296
- continue;
26297
- }
26298
- sanitizedObject[key] = sanitizeToolResultValue(entry, seen);
26291
+ /** The string a boxed `String` serializes to; JSON.stringify unboxes it only after the replacer has run. */
26292
+ function unboxedString(value) {
26293
+ if (typeof value === "string") return value;
26294
+ if (typeof value !== "object" || value === null) return void 0;
26295
+ try {
26296
+ String.prototype.valueOf.call(value);
26297
+ } catch {
26298
+ return;
26299
26299
  }
26300
- return sanitizedObject;
26300
+ return String(value);
26301
+ }
26302
+ /** Redacts long `encryptedContent` strings: opaque provider data that would otherwise dominate the count. */
26303
+ function redactEncryptedContent(key, value) {
26304
+ if (key !== ENCRYPTED_CONTENT_KEY) return value;
26305
+ const text = unboxedString(value);
26306
+ return text !== void 0 && text.length > ENCRYPTED_CONTENT_REDACTION_THRESHOLD ? `[stripped encryptedContent: ${text.length} characters]` : value;
26301
26307
  }
26302
26308
  /**
26303
26309
  * Serializes a tool result without truncating it.
@@ -26317,14 +26323,20 @@ function serializeToolResultForTokenCounting(value) {
26317
26323
  function toolErrorTextToString(errorText) {
26318
26324
  return errorText == null ? "" : stringifyToolResult(errorText);
26319
26325
  }
26326
+ /**
26327
+ * Serializes with `JSON.stringify` itself, the serializer storage uses, so a count of this text describes what
26328
+ * storage holds and a reload reads back (`toJSON()`, boxed primitives, class instances, array indices).
26329
+ */
26320
26330
  function stringifyToolResult(value) {
26321
26331
  if (typeof value === "string") return value;
26322
- const sanitized = sanitizeToolResultValue(value);
26332
+ let json;
26323
26333
  try {
26324
- return JSON.stringify(sanitized, null, 2);
26334
+ json = JSON.stringify(value, redactEncryptedContent, 2);
26325
26335
  } catch {
26326
- return String(sanitized);
26336
+ return String(value);
26327
26337
  }
26338
+ if (json === void 0) return "";
26339
+ return json.startsWith("\"") ? JSON.parse(json) : json;
26328
26340
  }
26329
26341
  function resolveToolResultValue(part, invocationResult) {
26330
26342
  const mastraMetadata = part?.providerMetadata?.mastra;
@@ -26338,13 +26350,58 @@ function resolveToolResultValue(part, invocationResult) {
26338
26350
  usingStoredModelOutput: false
26339
26351
  };
26340
26352
  }
26353
+ const PREFIX_CHUNK_MIN_LENGTH = 256;
26354
+ function isAsciiAlphanumeric(code) {
26355
+ return code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122;
26356
+ }
26357
+ function isSplitWhitespace(code) {
26358
+ return code === 32 || code === 10 || code === 9 || code === 13;
26359
+ }
26360
+ /**
26361
+ * Returns a function that counts `estimateTokenCount(text.slice(0, end) + suffix)` without rescanning the
26362
+ * whole prefix on every call.
26363
+ *
26364
+ * tokenx splits text into segments on whitespace and punctuation runs and sums a per-segment estimate.
26365
+ * Letters and digits are never separators and whitespace always is, so the position between an ASCII
26366
+ * letter or digit and a following whitespace character is always a segment boundary: the count of any
26367
+ * string that shares the text up to such a position equals the count before it plus the count after it.
26368
+ * The text is cut at those boundaries once, and each call only rescans the chunk it ends in.
26369
+ */
26370
+ function createPrefixTokenCounter(text) {
26371
+ const boundaries = [0];
26372
+ const tokensBefore = [0];
26373
+ let chunkStart = 0;
26374
+ let runningTokens = 0;
26375
+ 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))) {
26376
+ runningTokens += estimateTokenCount(text.slice(chunkStart, i));
26377
+ boundaries.push(i);
26378
+ tokensBefore.push(runningTokens);
26379
+ chunkStart = i;
26380
+ }
26381
+ return (end, suffix = "") => {
26382
+ let low = 0;
26383
+ let high = boundaries.length - 1;
26384
+ while (low < high) {
26385
+ const mid = low + high + 1 >> 1;
26386
+ if (boundaries[mid] <= end) low = mid;
26387
+ else high = mid - 1;
26388
+ }
26389
+ return tokensBefore[low] + estimateTokenCount(text.slice(boundaries[low], end) + suffix);
26390
+ };
26391
+ }
26341
26392
  function truncateStringByTokens(text, maxTokens) {
26342
26393
  if (!text || maxTokens <= 0) return "";
26343
- const totalTokens = estimateTokenCount(text);
26394
+ const countPrefixTokens = createPrefixTokenCounter(text);
26395
+ const totalTokens = countPrefixTokens(text.length);
26344
26396
  if (totalTokens <= maxTokens) return text;
26345
26397
  const buildCandidate = (sliceEnd) => {
26346
- const visible = safeSlice(text, sliceEnd);
26347
- return `${visible}\n... [truncated ~${totalTokens - estimateTokenCount(visible)} tokens]`;
26398
+ const visibleEnd = safeSlice(text, sliceEnd).length;
26399
+ const suffix = `\n... [truncated ~${totalTokens - countPrefixTokens(visibleEnd)} tokens]`;
26400
+ return {
26401
+ visibleEnd,
26402
+ suffix,
26403
+ tokens: countPrefixTokens(visibleEnd, suffix)
26404
+ };
26348
26405
  };
26349
26406
  let low = 0;
26350
26407
  let high = text.length;
@@ -26352,12 +26409,12 @@ function truncateStringByTokens(text, maxTokens) {
26352
26409
  while (low <= high) {
26353
26410
  const mid = Math.floor((low + high) / 2);
26354
26411
  const candidate = buildCandidate(mid);
26355
- if (estimateTokenCount(candidate) <= maxTokens) {
26412
+ if (candidate.tokens <= maxTokens) {
26356
26413
  best = candidate;
26357
26414
  low = mid + 1;
26358
26415
  } else high = mid - 1;
26359
26416
  }
26360
- return best;
26417
+ return text.slice(0, best.visibleEnd) + best.suffix;
26361
26418
  }
26362
26419
  function formatToolResultForObserver(value, options) {
26363
26420
  return truncateStringByTokens(stringifyToolResult(value), options?.maxTokens ?? 5e3);
@@ -28623,9 +28680,24 @@ function mergeCacheEntry(cache, key, entry) {
28623
28680
  function getPartCacheEntry(part, key) {
28624
28681
  return getCacheEntry(getPartMastraMetadata(part)?.tokenEstimate, key);
28625
28682
  }
28683
+ /**
28684
+ * Parts this process gave a new stored count. A part loaded from storage with its count is never in here,
28685
+ * so a message holding one of these parts has a count storage does not have yet.
28686
+ */
28687
+ const partsWithUnsavedCount = /* @__PURE__ */ new WeakSet();
28688
+ /** Whether `part` gained a stored count in this process that has not been handed to a save yet. */
28689
+ function hasUnsavedTokenEstimate(part) {
28690
+ return typeof part === "object" && part !== null && partsWithUnsavedCount.has(part);
28691
+ }
28692
+ /** Note that `part`'s count is on its way to storage, so later steps do not save it again. */
28693
+ function markTokenEstimateSaved(part) {
28694
+ if (typeof part === "object" && part !== null) partsWithUnsavedCount.delete(part);
28695
+ }
28696
+ const partCountMemo = /* @__PURE__ */ new WeakMap();
28626
28697
  function setPartCacheEntry(part, key, entry) {
28627
28698
  const mastraMetadata = ensurePartMastraMetadata(part);
28628
28699
  mastraMetadata.tokenEstimate = mergeCacheEntry(mastraMetadata.tokenEstimate, key, entry);
28700
+ partsWithUnsavedCount.add(part);
28629
28701
  }
28630
28702
  /**
28631
28703
  * Extracts a caller-supplied token estimate stamped on a part via
@@ -29319,14 +29391,19 @@ async function fetchGoogleAttachmentTokenEstimate(modelId, part) {
29319
29391
  * undercounted as generic JSON blobs.
29320
29392
  */
29321
29393
  var TokenCounter = class TokenCounter {
29322
- cacheSource;
29394
+ /**
29395
+ * Stored counts belong to the stock estimator. A subclass or instance that overrides `countString`
29396
+ * reads and writes its own namespace, so it never reuses a count the stock estimator saved.
29397
+ */
29398
+ get cacheSource() {
29399
+ return this.countString === TokenCounter.prototype.countString ? `v${TOKEN_ESTIMATE_CACHE_VERSION}:${resolveEstimatorId()}` : `v${TOKEN_ESTIMATE_CACHE_VERSION}:custom`;
29400
+ }
29323
29401
  defaultModelContext;
29324
29402
  inFlightAttachmentCounts = /* @__PURE__ */ new Map();
29325
29403
  multimodalToolResultCounts = /* @__PURE__ */ new WeakMap();
29326
29404
  static TOKENS_PER_MESSAGE = 3.8;
29327
29405
  static TOKENS_PER_CONVERSATION = 24;
29328
29406
  constructor(options) {
29329
- this.cacheSource = `v${TOKEN_ESTIMATE_CACHE_VERSION}:${resolveEstimatorId()}`;
29330
29407
  this.defaultModelContext = parseModelContext(options?.model);
29331
29408
  }
29332
29409
  runWithModelContext(model, fn) {
@@ -29357,6 +29434,28 @@ var TokenCounter = class TokenCounter {
29357
29434
  });
29358
29435
  return tokens;
29359
29436
  }
29437
+ /**
29438
+ * Count one content-only piece of a part (its text, a tool's args or result) the same way as
29439
+ * {@link readOrPersistPartEstimate}: a stored count is reused only when its content hash matches.
29440
+ * `refs` are the values the payload is built from. While the same part object still holds the same
29441
+ * refs, the count from the last call is returned without serializing or hashing again, so a part
29442
+ * counted by `getStatus` and then by the next step is hashed once per process.
29443
+ * Only string refs are memoized (object payloads are hashed every time, since they can change in place).
29444
+ */
29445
+ readOrPersistMemoizedPartEstimate(part, kind, refs, getPayload) {
29446
+ if (!refs.every((ref) => typeof ref === "string")) return this.readOrPersistPartEstimate(part, kind, getPayload());
29447
+ let byKind = partCountMemo.get(part);
29448
+ const memo = byKind?.get(kind);
29449
+ if (memo && memo.owner === this && memo.refs.length === refs.length && memo.refs.every((ref, i) => ref === refs[i])) return memo.tokens;
29450
+ const tokens = this.readOrPersistPartEstimate(part, kind, getPayload());
29451
+ if (!byKind) partCountMemo.set(part, byKind = /* @__PURE__ */ new Map());
29452
+ byKind.set(kind, {
29453
+ owner: this,
29454
+ refs,
29455
+ tokens
29456
+ });
29457
+ return tokens;
29458
+ }
29360
29459
  readOrPersistFixedPartEstimate(part, kind, payload, tokens) {
29361
29460
  const key = buildEstimateKey(kind, payload);
29362
29461
  const cached = getPartCacheEntry(part, key);
@@ -29707,18 +29806,23 @@ var TokenCounter = class TokenCounter {
29707
29806
  /**
29708
29807
  * Count the name and the arguments of a tool call. Every state before the tool produces an
29709
29808
  * output holds the same call signature in the context window, so all of those states share
29710
- * these cache kinds. `buildEstimateKey` hashes the text, so a shared kind stays correct and
29711
- * keeps the estimate warm while the invocation moves from one state to the next.
29809
+ * these cache kinds, and the estimate stays warm while the invocation moves from one state to
29810
+ * the next. Name and args don't change across those states once the call stops streaming.
29712
29811
  */
29713
29812
  countToolCallSignature(part, invocation) {
29714
29813
  let tokens = 0;
29715
29814
  let overheadDelta = 0;
29716
- if (invocation.toolName) tokens += this.readOrPersistPartEstimate(part, "tool-call-name", invocation.toolName);
29815
+ const storable = invocation.state !== "partial-call";
29816
+ const count = (kind, ref, getPayload) => storable ? this.readOrPersistMemoizedPartEstimate(part, kind, [ref], getPayload) : this.readOrPersistPartEstimate(part, kind, getPayload());
29817
+ if (invocation.toolName) {
29818
+ const toolName = invocation.toolName;
29819
+ tokens += count("tool-call-name", toolName, () => toolName);
29820
+ }
29717
29821
  if (invocation.args !== void 0) {
29718
- if (typeof invocation.args === "string") tokens += this.readOrPersistPartEstimate(part, "tool-call-args", invocation.args);
29822
+ const args = invocation.args;
29823
+ if (typeof args === "string") tokens += count("tool-call-args", args, () => args);
29719
29824
  else {
29720
- const argsJson = JSON.stringify(invocation.args);
29721
- tokens += this.readOrPersistPartEstimate(part, "tool-call-args-json", argsJson);
29825
+ tokens += count("tool-call-args-json", args, () => JSON.stringify(args));
29722
29826
  overheadDelta -= 12;
29723
29827
  }
29724
29828
  }
@@ -29730,11 +29834,14 @@ var TokenCounter = class TokenCounter {
29730
29834
  countNonAttachmentPart(part) {
29731
29835
  let overheadDelta = 0;
29732
29836
  let extraMessageDelta = 0;
29733
- if (part.type === "text") return {
29734
- tokens: this.readOrPersistPartEstimate(part, "text", part.text),
29735
- overheadDelta,
29736
- extraMessageDelta
29737
- };
29837
+ if (part.type === "text") {
29838
+ const text = part.text;
29839
+ return {
29840
+ tokens: this.readOrPersistMemoizedPartEstimate(part, "text", [text], () => text),
29841
+ overheadDelta,
29842
+ extraMessageDelta
29843
+ };
29844
+ }
29738
29845
  if (part.type === "tool-invocation") {
29739
29846
  const invocation = part.toolInvocation;
29740
29847
  const state = invocation.state;
@@ -29753,7 +29860,7 @@ var TokenCounter = class TokenCounter {
29753
29860
  tokens += signature.tokens;
29754
29861
  overheadDelta += signature.overheadDelta;
29755
29862
  const reason = invocation.approval?.reason;
29756
- if (reason) tokens += this.readOrPersistPartEstimate(part, "tool-approval-reason", reason);
29863
+ if (reason) tokens += this.readOrPersistMemoizedPartEstimate(part, "tool-approval-reason", [reason], () => reason);
29757
29864
  return {
29758
29865
  tokens,
29759
29866
  overheadDelta,
@@ -29769,15 +29876,12 @@ var TokenCounter = class TokenCounter {
29769
29876
  if (resultForCounting !== void 0 && (typeof resultForCounting !== "string" || resultForCounting.trim().length > 0)) {
29770
29877
  const contentTokens = this.countMultimodalToolResultContent(part, resultForCounting);
29771
29878
  if (contentTokens !== void 0) tokens += contentTokens;
29772
- else {
29773
- const formattedResult = serializeToolResultForTokenCounting(resultForCounting);
29774
- tokens += this.readOrPersistPartEstimate(part, usingStoredModelOutput ? "tool-result-model-output-json" : "tool-result-json", formattedResult);
29775
- }
29879
+ else tokens += this.readOrPersistMemoizedPartEstimate(part, usingStoredModelOutput ? "tool-result-model-output-json" : "tool-result-json", [resultForCounting], () => serializeToolResultForTokenCounting(resultForCounting));
29776
29880
  if (typeof resultForCounting !== "string") overheadDelta -= 12;
29777
29881
  } else {
29778
29882
  const errorText = toolErrorTextToString(invocation.errorText);
29779
29883
  const fallback = invocation.isError ? errorText.trim() ? errorText : "Tool execution failed" : "[empty result]";
29780
- tokens += this.readOrPersistPartEstimate(part, invocation.isError ? "tool-result-error" : "tool-result-json", fallback);
29884
+ tokens += this.readOrPersistMemoizedPartEstimate(part, invocation.isError ? "tool-result-error" : "tool-result-json", [fallback], () => fallback);
29781
29885
  }
29782
29886
  return {
29783
29887
  tokens,
@@ -29791,7 +29895,7 @@ var TokenCounter = class TokenCounter {
29791
29895
  tokens += signature.tokens;
29792
29896
  overheadDelta += signature.overheadDelta;
29793
29897
  const reason = invocation.approval?.reason?.trim() ? invocation.approval.reason : "Tool call was not approved by the user";
29794
- tokens += this.readOrPersistPartEstimate(part, "tool-result-denied", reason);
29898
+ tokens += this.readOrPersistMemoizedPartEstimate(part, "tool-result-denied", [reason], () => reason);
29795
29899
  return {
29796
29900
  tokens,
29797
29901
  overheadDelta,
@@ -29805,7 +29909,7 @@ var TokenCounter = class TokenCounter {
29805
29909
  overheadDelta += signature.overheadDelta;
29806
29910
  const errorText = toolErrorTextToString(invocation.errorText);
29807
29911
  const errorMessage = errorText.trim() ? errorText : "Tool execution failed";
29808
- tokens += this.readOrPersistPartEstimate(part, "tool-result-error", errorMessage);
29912
+ tokens += this.readOrPersistMemoizedPartEstimate(part, "tool-result-error", [errorMessage], () => errorMessage);
29809
29913
  return {
29810
29914
  tokens,
29811
29915
  overheadDelta,
@@ -29818,6 +29922,11 @@ var TokenCounter = class TokenCounter {
29818
29922
  overheadDelta,
29819
29923
  extraMessageDelta
29820
29924
  };
29925
+ if (part.type === "step-start") return {
29926
+ tokens: 0,
29927
+ overheadDelta,
29928
+ extraMessageDelta
29929
+ };
29821
29930
  if (part.type === "reasoning") return {
29822
29931
  tokens: 0,
29823
29932
  overheadDelta,
@@ -33229,6 +33338,7 @@ const threadTitleInstructions = `A short, noun-phrase title for this conversatio
33229
33338
  - "Auth bug fix" \u2014 not "Fixing the auth bug"
33230
33339
  - "Dark mode toggle" \u2014 not "User wants dark mode toggle added"
33231
33340
  - "Deployment pipeline setup" \u2014 not "Setting up deployment pipeline for project"
33341
+ Write the title in the same language the user's messages are written in.
33232
33342
  Only update when the topic meaningfully changes.`;
33233
33343
  function createCurrentTaskExtractor() {
33234
33344
  return new Extractor({
@@ -35190,6 +35300,47 @@ ObservationStrategy.create = ((om, opts) => {
35190
35300
  if (deps.scope === "resource" && opts.resourceId) return new ResourceScopedObservationStrategy(deps, opts);
35191
35301
  return new SyncObservationStrategy(deps, opts);
35192
35302
  });
35303
+ // src/processors/observational-memory/resave-counted-messages.ts
35304
+ /**
35305
+ * Mark the stored history of `threadId` in `messageList` that OM gave new token counts, so the counts are saved
35306
+ * with the messages. Call the returned function once the counting is done: every message holding a part that
35307
+ * gained a count in this process is marked for resave, and the normal save writes it back whole. Counts made
35308
+ * before this is called (while the turn loaded history) are caught too.
35309
+ *
35310
+ * Only messages of `threadId` are marked. A message recalled from another thread of the resource is counted but
35311
+ * never written, because saving it would bump that thread's `updatedAt` and reorder the recent-thread list.
35312
+ *
35313
+ * A Core without `markForResave` is left alone: counting still works, the counts are just not saved.
35314
+ */
35315
+ function resaveCountedMessagesFor(messageList, threadId) {
35316
+ if (typeof messageList.markForResave !== "function") return () => {};
35317
+ return () => {
35318
+ for (const message of messageList.get.remembered.db()) {
35319
+ if (message.threadId !== threadId) continue;
35320
+ const parts = message.content?.parts ?? [];
35321
+ if (!parts.some(hasUnsavedTokenEstimate)) continue;
35322
+ messageList.markForResave(message);
35323
+ parts.forEach(markTokenEstimateSaved);
35324
+ }
35325
+ };
35326
+ }
35327
+ /** The stored messages marked for resave in `messageList`; none for a Core without `markForResave`. */
35328
+ function messagesMarkedForResave(messageList) {
35329
+ return typeof messageList.getMessagesToResave === "function" ? messageList.getMessagesToResave() : [];
35330
+ }
35331
+ /**
35332
+ * Ids of the stored messages marked for resave in `messageList` that are not in `ownMessages` (the turn's
35333
+ * own input and output). Those are saved whole; the rest only gained counts and are patched onto storage.
35334
+ */
35335
+ function idsMarkedForResave(messageList, ownMessages = []) {
35336
+ const own = new Set(ownMessages.map((message) => message.id));
35337
+ return new Set(messagesMarkedForResave(messageList).map((message) => message.id).filter((id) => !own.has(id)));
35338
+ }
35339
+ /** `messages` with the messages marked for resave added, each message once. */
35340
+ function withMessagesMarkedForResave(messageList, messages) {
35341
+ const ids = new Set(messages.map((message) => message.id));
35342
+ return [...messages, ...messagesMarkedForResave(messageList).filter((message) => !ids.has(message.id))];
35343
+ }
35193
35344
  // src/processors/observational-memory/observation-turn/load-memory-context.ts
35194
35345
  async function loadMemoryContextMessages({ memory, messageList, threadId, resourceId, runState }) {
35195
35346
  const ctx = await memory.getContext({
@@ -35197,7 +35348,8 @@ async function loadMemoryContextMessages({ memory, messageList, threadId, resour
35197
35348
  resourceId,
35198
35349
  runState
35199
35350
  });
35200
- for (const msg of ctx.messages) if (msg.role !== "system") messageList.add(msg, "memory");
35351
+ const messages = ctx.messages.filter((msg) => msg.role !== "system");
35352
+ if (messages.length) messageList.add(messages, "memory");
35201
35353
  return ctx;
35202
35354
  }
35203
35355
  // src/processors/observational-memory/observation-turn/safe-buffer-prefix.ts
@@ -35404,7 +35556,7 @@ var ObservationStep = class {
35404
35556
  const inputIds = new Set(messageList.get.input.db().map((msg) => msg.id));
35405
35557
  const sealedOutput = safeCandidates.filter((msg) => !inputIds.has(msg.id));
35406
35558
  messageList.removeByIds(sealedOutput.map((msg) => msg.id));
35407
- for (const msg of sealedOutput) messageList.add(msg, "memory");
35559
+ if (sealedOutput.length) messageList.add(sealedOutput, "memory");
35408
35560
  }
35409
35561
  if (!deferred) {
35410
35562
  om.trackBackgroundWork(om.buffer({
@@ -35453,7 +35605,7 @@ var ObservationStep = class {
35453
35605
  }).map((msg) => msg.id);
35454
35606
  inFlightIds = [...new Set(unreadIds)];
35455
35607
  if (messagesToSave.length > 0) {
35456
- for (const msg of messagesToSave) messageList.add(msg, "memory");
35608
+ messageList.add(messagesToSave, "memory");
35457
35609
  try {
35458
35610
  await om.persistMessages(messagesToSave, threadId, resourceId);
35459
35611
  } catch (error) {
@@ -35956,8 +36108,8 @@ var ObservationTurn = class {
35956
36108
  this._ended = true;
35957
36109
  const unsavedInput = messageList.get.input.db();
35958
36110
  const unsavedOutput = messageList.get.response.db();
35959
- const unsavedMessages = [...unsavedInput, ...unsavedOutput];
35960
- if (unsavedMessages.length > 0) await this.om.persistMessages(unsavedMessages, this.threadId, this.resourceId);
36111
+ const unsavedMessages = withMessagesMarkedForResave(messageList, [...unsavedInput, ...unsavedOutput]);
36112
+ if (unsavedMessages.length > 0) await this.om.persistMessages(unsavedMessages, this.threadId, this.resourceId, idsMarkedForResave(messageList, [...unsavedInput, ...unsavedOutput]));
35961
36113
  const asyncObservationEnabled = this.om.buffering.isAsyncObservationEnabled();
35962
36114
  const bufferOnIdle = this.om.getObservationConfig().bufferOnIdle;
35963
36115
  if (!this.abortSignal?.aborted && asyncObservationEnabled && bufferOnIdle) {
@@ -38866,18 +39018,86 @@ var ObservationalMemory = class ObservationalMemory {
38866
39018
  * to detect already-persisted messages, avoiding redundant DB operations.
38867
39019
  *
38868
39020
  * Messages with observation markers are always saved (upserted) even if sealed,
38869
- * because the markers need to be persisted to storage.
39021
+ * because the markers need to be persisted to storage. A stored message in `resaveIds` gained token
39022
+ * counts after it was stored, whether or not it is sealed: only those counts are copied onto the stored
39023
+ * 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
39024
+ * input or output, which are saved whole.
38870
39025
  */
38871
- async persistMessages(messagesToSave, threadId, resourceId) {
39026
+ async persistMessages(messagesToSave, threadId, resourceId, resaveIds) {
38872
39027
  const filteredMessages = [];
38873
- for (const msg of messagesToSave) if (!!(msg.content?.metadata)?.mastra?.sealed) {
38874
- if (findLastCompletedObservationBoundary(msg) !== -1) filteredMessages.push(msg);
38875
- } else filteredMessages.push(msg);
39028
+ const storedWithNewCounts = [];
39029
+ for (const msg of messagesToSave) {
39030
+ if (!!(msg.content?.metadata)?.mastra?.sealed && findLastCompletedObservationBoundary(msg) === -1 && !resaveIds?.has(msg.id)) continue;
39031
+ if (resaveIds?.has(msg.id) && findLastCompletedObservationBoundary(msg) === -1) storedWithNewCounts.push(msg);
39032
+ else filteredMessages.push(msg);
39033
+ }
38876
39034
  if (filteredMessages.length > 0) await this.messageHistory.persistMessages({
38877
39035
  messages: filteredMessages,
38878
39036
  threadId,
38879
39037
  resourceId
38880
39038
  });
39039
+ try {
39040
+ await this.persistTokenEstimatesOntoStored(storedWithNewCounts);
39041
+ } catch (error) {
39042
+ omError("[OM] Failed to save token counts for stored messages", error);
39043
+ }
39044
+ }
39045
+ /**
39046
+ * Copy the token counts of `messages` onto their stored copies. A stored copy can hold
39047
+ * parts the in-memory one lacks (markers written straight to storage), so it is patched
39048
+ * instead of saved whole. Each count goes to the first stored part whose content matches the counted
39049
+ * part, so a part that changed in storage keeps no count and is counted again on read.
39050
+ */
39051
+ async persistTokenEstimatesOntoStored(messages) {
39052
+ if (messages.length === 0) return;
39053
+ const contentOf = (part) => {
39054
+ const { tokenEstimate: _tokenEstimate, ...mastra } = part.providerMetadata?.mastra ?? {};
39055
+ return JSON.stringify({
39056
+ ...part,
39057
+ providerMetadata: {
39058
+ ...part.providerMetadata,
39059
+ mastra
39060
+ }
39061
+ });
39062
+ };
39063
+ const live = new Map(messages.map((message) => [message.id, message]));
39064
+ const { messages: stored } = await this.storage.listMessagesById({ messageIds: [...live.keys()] });
39065
+ const updates = [];
39066
+ for (const row of stored) {
39067
+ const counts = /* @__PURE__ */ new Map();
39068
+ for (const part of live.get(row.id)?.content.parts ?? []) {
39069
+ const tokenEstimate = part.providerMetadata?.mastra?.tokenEstimate;
39070
+ if (!tokenEstimate) continue;
39071
+ const key = contentOf(part);
39072
+ counts.set(key, [...counts.get(key) ?? [], tokenEstimate]);
39073
+ }
39074
+ if (counts.size === 0) continue;
39075
+ let changed = false;
39076
+ const parts = row.content.parts.map((part) => {
39077
+ const tokenEstimate = counts.get(contentOf(part))?.shift();
39078
+ if (!tokenEstimate) return part;
39079
+ changed = true;
39080
+ const providerMetadata = part.providerMetadata ?? {};
39081
+ return {
39082
+ ...part,
39083
+ providerMetadata: {
39084
+ ...providerMetadata,
39085
+ mastra: {
39086
+ ...providerMetadata.mastra,
39087
+ tokenEstimate
39088
+ }
39089
+ }
39090
+ };
39091
+ });
39092
+ if (changed) updates.push({
39093
+ id: row.id,
39094
+ content: {
39095
+ ...row.content,
39096
+ parts
39097
+ }
39098
+ });
39099
+ }
39100
+ if (updates.length > 0) await this.storage.updateMessages({ messages: updates });
38881
39101
  }
38882
39102
  /**
38883
39103
  * Load messages from storage that haven't been observed yet.
@@ -40680,11 +40900,12 @@ var ObservationalMemoryProcessor = class {
40680
40900
  state.__omTurn = void 0;
40681
40901
  if (!activeTurn || activeTurn.ended) return;
40682
40902
  const terminalList = messageList ?? activeTurn.messageList;
40683
- const unsavedMessages = [...terminalList.get.input.db(), ...terminalList.get.response.db()];
40903
+ const ownMessages = [...terminalList.get.input.db(), ...terminalList.get.response.db()];
40904
+ const unsavedMessages = withMessagesMarkedForResave(terminalList, ownMessages);
40684
40905
  try {
40685
40906
  await activeTurn.end(terminalList);
40686
40907
  } catch (error) {
40687
- if (unsavedMessages.length > 0) await this.engine.persistMessages(unsavedMessages, activeTurn.threadId, activeTurn.resourceId).catch(() => {});
40908
+ if (unsavedMessages.length > 0) await this.engine.persistMessages(unsavedMessages, activeTurn.threadId, activeTurn.resourceId, idsMarkedForResave(terminalList, ownMessages)).catch(() => {});
40688
40909
  throw error;
40689
40910
  }
40690
40911
  }
@@ -40826,6 +41047,7 @@ var ObservationalMemoryProcessor = class {
40826
41047
  this.turn.responseMessageId = responseMessageId;
40827
41048
  {
40828
41049
  const step = this.turn.step(stepNumber);
41050
+ const resaveCounted = resaveCountedMessagesFor(messageList, threadId);
40829
41051
  let ctx;
40830
41052
  try {
40831
41053
  ctx = await step.prepare();
@@ -40860,6 +41082,7 @@ var ObservationalMemoryProcessor = class {
40860
41082
  threadId,
40861
41083
  resourceId
40862
41084
  });
41085
+ resaveCounted();
40863
41086
  const finalTotalPending = ctx.status.pendingTokens;
40864
41087
  try {
40865
41088
  await runOMCommit(this.engine.buffering.getLockKey(threadId, resourceId), () => this.engine.getStorage().setPendingMessageTokens(turnRecord.id, finalTotalPending), { abortSignal });
@@ -40899,6 +41122,7 @@ var ObservationalMemoryProcessor = class {
40899
41122
  return this.engine.getTokenCounter().runWithModelContext(state.__omActorModelContext, async () => {
40900
41123
  if (parseMemoryRequestContext(requestContext)?.memoryConfig?.readOnly) return messageList;
40901
41124
  const persistenceMessageList = messageList.cloneForPersistence();
41125
+ this.engine.getTokenCounter().countMessages(persistenceMessageList.get.response.db());
40902
41126
  const turn = asLiveTurn(state.__omTurn) ?? this.turn;
40903
41127
  const liveTurn = turn && !turn.ended ? turn : void 0;
40904
41128
  if (liveTurn) await liveTurn.end(persistenceMessageList);
@@ -40906,8 +41130,9 @@ var ObservationalMemoryProcessor = class {
40906
41130
  state.__omTurn = void 0;
40907
41131
  if (!liveTurn) {
40908
41132
  const newOutput = persistenceMessageList.get.response.db();
40909
- const messagesToSave = [...persistenceMessageList.get.input.db(), ...newOutput];
40910
- if (messagesToSave.length > 0 && context.threadId) await this.engine.persistMessages(messagesToSave, context.threadId, context.resourceId);
41133
+ const ownMessages = [...persistenceMessageList.get.input.db(), ...newOutput];
41134
+ const messagesToSave = withMessagesMarkedForResave(persistenceMessageList, ownMessages);
41135
+ if (messagesToSave.length > 0 && context.threadId) await this.engine.persistMessages(messagesToSave, context.threadId, context.resourceId, idsMarkedForResave(persistenceMessageList, ownMessages));
40911
41136
  }
40912
41137
  return messageList;
40913
41138
  });