@mastra/server 1.86.0-alpha.8 → 1.86.0-alpha.9

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.
Files changed (90) hide show
  1. package/dist/{a2a-BfWMjFe2.js → a2a-CY7rgzPe.js} +1 -1
  2. package/dist/{a2a-DQIwTZyo.cjs → a2a-DwjvHqcb.cjs} +1 -1
  3. package/dist/{agent-builder-DpuK5-6A.js → agent-builder-DHnNRROR.js} +1 -1
  4. package/dist/{agent-builder-NSemjs4B.cjs → agent-builder-anRH1X35.cjs} +1 -1
  5. package/dist/{agents-YvaBPFiS.js → agents-CAXsXenf.js} +18 -0
  6. package/dist/{agents-BO1mcMDf.cjs → agents-GHhuyz5x.cjs} +18 -0
  7. package/dist/{api-schema-manifest-CAZsA5Lk.js → api-schema-manifest-4PK1dBWt.js} +1 -1
  8. package/dist/{api-schema-manifest-016lHJO2.cjs → api-schema-manifest-CX16hC7V.cjs} +1 -1
  9. package/dist/{auth-CM5AgF9l.cjs → auth-BR7vRIrY.cjs} +5 -3
  10. package/dist/{auth-CjT_a76k.js → auth-ChZ3dUvo.js} +5 -3
  11. package/dist/{catalogue-DN4dvU88.js → catalogue-BOzHZ1xt.js} +5 -5
  12. package/dist/{catalogue-Cf7Zz7zb.cjs → catalogue-DNy7Fog6.cjs} +5 -5
  13. package/dist/{conversations-4ZO0Pjvk.js → conversations-BjD8wOc3.js} +1 -1
  14. package/dist/{conversations-BaYtooZZ.cjs → conversations-CgogBOHO.cjs} +1 -1
  15. package/dist/dist-BWVxgpEw.js +1 -0
  16. package/dist/{dist-DaRCrkAU.cjs → dist-Brw_H26B.cjs} +296 -72
  17. package/dist/{dist-uiPbWl5E.cjs → dist-C5_WGwU1.cjs} +1 -1
  18. package/dist/{dist-yny1avqv.js → dist-NBGkHBIE.js} +296 -72
  19. package/dist/docs/SKILL.md +1 -1
  20. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  21. package/dist/docs/references/docs-knowledge-overview.md +1 -1
  22. package/dist/{editor-builder-CwsIbd0F.js → editor-builder-BRzXnsRW.js} +1 -1
  23. package/dist/{editor-builder-ChYG8YTs.cjs → editor-builder-G1ub9j0s.cjs} +1 -1
  24. package/dist/{knowledge-DL03nbSW.cjs → knowledge-B3768ERP.cjs} +1 -0
  25. package/dist/{knowledge-DAqUHFK5.js → knowledge-wqC0nrmu.js} +1 -0
  26. package/dist/{plans-CbR8EDiT.js → plans-DGC1grMp.js} +1 -1
  27. package/dist/{plans-k3UN9Nd1.cjs → plans-kA8E3Auv.cjs} +1 -1
  28. package/dist/{probe-image-size-z8zXmjaH.cjs → probe-image-size-ntJyQKKB.cjs} +1 -1
  29. package/dist/{probe-image-size-DZvSdjzK.js → probe-image-size-zXQBlFaQ.js} +1 -1
  30. package/dist/{responses-Blzxy0XP.js → responses--nGf7l3O.js} +1 -1
  31. package/dist/{responses-B-BKx236.cjs → responses-B4GDz-Nm.cjs} +1 -1
  32. package/dist/{routes-D-I2voQe.js → routes-BZVlqLly.js} +12 -12
  33. package/dist/{routes-jiZyt9kU.cjs → routes-vuZLexcc.cjs} +12 -12
  34. package/dist/{scores-DAv6Uisq.js → scores-Biv7XGW_.js} +1 -1
  35. package/dist/{scores-BikU9phm.cjs → scores-D0Qq7TfU.cjs} +1 -1
  36. package/dist/server/handlers/a2a.cjs +1 -1
  37. package/dist/server/handlers/a2a.js +1 -1
  38. package/dist/server/handlers/agent-builder.cjs +1 -1
  39. package/dist/server/handlers/agent-builder.js +1 -1
  40. package/dist/server/handlers/agents.cjs +1 -1
  41. package/dist/server/handlers/agents.js +1 -1
  42. package/dist/server/handlers/auth.cjs +6 -2
  43. package/dist/server/handlers/auth.d.ts +12 -4
  44. package/dist/server/handlers/auth.js +6 -2
  45. package/dist/server/handlers/conversations.cjs +1 -1
  46. package/dist/server/handlers/conversations.js +1 -1
  47. package/dist/server/handlers/editor-builder.cjs +1 -1
  48. package/dist/server/handlers/editor-builder.js +1 -1
  49. package/dist/server/handlers/error.cjs +1 -1
  50. package/dist/server/handlers/error.js +1 -1
  51. package/dist/server/handlers/favorites-enrichment.cjs +1 -1
  52. package/dist/server/handlers/favorites-enrichment.js +1 -1
  53. package/dist/server/handlers/knowledge.cjs +1 -1
  54. package/dist/server/handlers/knowledge.js +1 -1
  55. package/dist/server/handlers/plans.cjs +1 -1
  56. package/dist/server/handlers/plans.js +1 -1
  57. package/dist/server/handlers/responses.cjs +1 -1
  58. package/dist/server/handlers/responses.js +1 -1
  59. package/dist/server/handlers/scores.cjs +1 -1
  60. package/dist/server/handlers/scores.js +1 -1
  61. package/dist/server/handlers/stored-agent-favorites.cjs +1 -1
  62. package/dist/server/handlers/stored-agent-favorites.js +1 -1
  63. package/dist/server/handlers/stored-agents.cjs +1 -1
  64. package/dist/server/handlers/stored-agents.js +1 -1
  65. package/dist/server/handlers/stored-skill-favorites.cjs +1 -1
  66. package/dist/server/handlers/stored-skill-favorites.js +1 -1
  67. package/dist/server/handlers/stored-skills.cjs +1 -1
  68. package/dist/server/handlers/stored-skills.js +1 -1
  69. package/dist/server/handlers/system.cjs +1 -1
  70. package/dist/server/handlers/system.js +1 -1
  71. package/dist/server/handlers/tools.cjs +1 -1
  72. package/dist/server/handlers/tools.js +1 -1
  73. package/dist/server/handlers/voice.cjs +1 -1
  74. package/dist/server/handlers/voice.js +1 -1
  75. package/dist/server/handlers.cjs +9 -9
  76. package/dist/server/handlers.js +9 -9
  77. package/dist/server/schemas/auth.d.ts +3 -1
  78. package/dist/server/schemas/index.cjs +1 -1
  79. package/dist/server/schemas/index.js +1 -1
  80. package/dist/server/server-adapter/index.cjs +2 -2
  81. package/dist/server/server-adapter/index.js +2 -2
  82. package/dist/server/server-adapter/routes/conversations.d.ts +3 -3
  83. package/dist/{server-adapter-BB2Lw2Ig.cjs → server-adapter-CurME3ch.cjs} +1 -1
  84. package/dist/{server-adapter-CMJcvkpD.js → server-adapter-h8YRQXAC.js} +1 -1
  85. package/dist/{tools-CoamSJif.cjs → tools-By0RVh_O.cjs} +1 -1
  86. package/dist/{tools-DsSk01Ti.js → tools-C3KBdlil.js} +1 -1
  87. package/dist/{voice-CquR7YyA.cjs → voice-CESew8Fc.cjs} +1 -1
  88. package/dist/{voice-BFh2Zx5m.js → voice-PfxY_vQg.js} +1 -1
  89. package/package.json +3 -3
  90. package/dist/dist-Bz6gINFc.js +0 -1
@@ -8655,7 +8655,7 @@ function splitLines(text) {
8655
8655
  else result.push(result.pop().slice(0, -1));
8656
8656
  return result;
8657
8657
  }
8658
- // ../memory/dist/src-TRQ73bGO.js
8658
+ // ../memory/dist/src-C6oJP8WI.js
8659
8659
  var __defProp$3 = Object.defineProperty;
8660
8660
  var __exportAll = (all, no_symbols) => {
8661
8661
  let target = {};
@@ -33639,6 +33639,17 @@ function isTransientLLMError(error) {
33639
33639
  return visit(error);
33640
33640
  }
33641
33641
  /**
33642
+ * Returns true when the error says the provider account has no credits or quota left, as core's
33643
+ * provider-error classifier decides it. These can carry a retryable status (OpenAI's are HTTP 429,
33644
+ * the status of a rate limit), so `withRetry` stops on them even though `isTransientLLMError`
33645
+ * matches: the account stays unusable until someone adds credits. Rate limits are still retried.
33646
+ *
33647
+ * @internal
33648
+ */
33649
+ function isExhaustedAccountError(error) {
33650
+ return classifyProviderError(error) === "quota";
33651
+ }
33652
+ /**
33642
33653
  * Compute the backoff delay (ms) for the Nth retry (0-indexed).
33643
33654
  *
33644
33655
  * Exponential growth (`initialDelayMs * backoffFactor^attempt`) capped at
@@ -33722,7 +33733,8 @@ async function attemptWithIdleTimeout(fn, label, idleTimeoutMs, abortSignal) {
33722
33733
  /**
33723
33734
  * Run `fn` with retries on transient transport-class errors.
33724
33735
  *
33725
- * Non-transient errors (auth, validation, schema, etc.) are rethrown
33736
+ * Non-transient errors (auth, validation, schema, etc.) and errors from an
33737
+ * account with no credits or quota left (see `isExhaustedAccountError`) are rethrown
33726
33738
  * immediately. User-initiated aborts are rethrown without delay.
33727
33739
  *
33728
33740
  * @internal
@@ -33738,7 +33750,7 @@ async function withRetry(fn, opts) {
33738
33750
  } catch (error) {
33739
33751
  if (abortSignal?.aborted) throw error;
33740
33752
  if (!(error instanceof OmModelCallTimeoutError) && hasAbortInChain(error)) throw error;
33741
- if (attempt >= maxRetries || !isTransientLLMError(error)) {
33753
+ if (attempt >= maxRetries || !isTransientLLMError(error) || isExhaustedAccountError(error)) {
33742
33754
  if (attempt > 0) omDebug(`[OM:retry:${label}] giving up after ${attempt} retry/retries: ${error instanceof Error ? error.message : String(error)}`);
33743
33755
  throw error;
33744
33756
  }
@@ -34484,7 +34496,7 @@ const OBSERVER_TOOL_ARGUMENT_MAX_DEPTH = 5;
34484
34496
  const OBSERVER_TOOL_ARGUMENT_MAX_ENTRIES_PER_CONTAINER = 20;
34485
34497
  const OBSERVER_TOOL_ARGUMENT_MAX_OUTLINE_ENTRIES = 100;
34486
34498
  const OBSERVER_TOOL_ARGUMENT_MAX_PATH_CHARS = 160;
34487
- function isObjectLike$1(value) {
34499
+ function isObjectLike(value) {
34488
34500
  return typeof value === "object" && value !== null;
34489
34501
  }
34490
34502
  function sanitizeSurrogates(value) {
@@ -34670,7 +34682,7 @@ function formatToolArgumentsForObserver(value, options) {
34670
34682
  maxCharacters: options?.maxCharacters ?? Number.POSITIVE_INFINITY
34671
34683
  };
34672
34684
  if (limits.maxTokens <= 0 || limits.maxCharacters <= 0) return "";
34673
- if (!isObjectLike$1(value)) {
34685
+ if (!isObjectLike(value)) {
34674
34686
  if (typeof value !== "string" || value.length <= OBSERVER_TOOL_ARGUMENT_INLINE_STRING_MAX_CHARS) {
34675
34687
  const primitive = formatPrimitive(value);
34676
34688
  return fits(primitive, limits) ? primitive : fits("\u2026", limits) ? "\u2026" : "";
@@ -34749,7 +34761,7 @@ function formatToolArgumentsForObserver(value, options) {
34749
34761
  });
34750
34762
  continue;
34751
34763
  }
34752
- if (!isObjectLike$1(entryValue)) {
34764
+ if (!isObjectLike(entryValue)) {
34753
34765
  outline.push({
34754
34766
  text: `${path}: ${formatPrimitive(entryValue)}`,
34755
34767
  depth: current.depth,
@@ -34830,28 +34842,22 @@ function formatToolArgumentsForObserver(value, options) {
34830
34842
  }
34831
34843
  const ENCRYPTED_CONTENT_KEY = "encryptedContent";
34832
34844
  const ENCRYPTED_CONTENT_REDACTION_THRESHOLD = 256;
34833
- function isObjectLike(value) {
34834
- return typeof value === "object" && value !== null;
34835
- }
34836
- function sanitizeToolResultValue(value, seen = /* @__PURE__ */ new WeakMap()) {
34837
- if (!isObjectLike(value)) return value;
34838
- if (seen.has(value)) return seen.get(value);
34839
- if (Array.isArray(value)) {
34840
- const sanitizedArray = [];
34841
- seen.set(value, sanitizedArray);
34842
- for (const item of value) sanitizedArray.push(sanitizeToolResultValue(item, seen));
34843
- return sanitizedArray;
34844
- }
34845
- const sanitizedObject = {};
34846
- seen.set(value, sanitizedObject);
34847
- for (const [key, entry] of Object.entries(value)) {
34848
- if (key === ENCRYPTED_CONTENT_KEY && typeof entry === "string" && entry.length > ENCRYPTED_CONTENT_REDACTION_THRESHOLD) {
34849
- sanitizedObject[key] = `[stripped encryptedContent: ${entry.length} characters]`;
34850
- continue;
34851
- }
34852
- sanitizedObject[key] = sanitizeToolResultValue(entry, seen);
34845
+ /** The string a boxed `String` serializes to; JSON.stringify unboxes it only after the replacer has run. */
34846
+ function unboxedString(value) {
34847
+ if (typeof value === "string") return value;
34848
+ if (typeof value !== "object" || value === null) return void 0;
34849
+ try {
34850
+ String.prototype.valueOf.call(value);
34851
+ } catch {
34852
+ return;
34853
34853
  }
34854
- return sanitizedObject;
34854
+ return String(value);
34855
+ }
34856
+ /** Redacts long `encryptedContent` strings: opaque provider data that would otherwise dominate the count. */
34857
+ function redactEncryptedContent(key, value) {
34858
+ if (key !== ENCRYPTED_CONTENT_KEY) return value;
34859
+ const text = unboxedString(value);
34860
+ return text !== void 0 && text.length > ENCRYPTED_CONTENT_REDACTION_THRESHOLD ? `[stripped encryptedContent: ${text.length} characters]` : value;
34855
34861
  }
34856
34862
  /**
34857
34863
  * Serializes a tool result without truncating it.
@@ -34871,14 +34877,20 @@ function serializeToolResultForTokenCounting(value) {
34871
34877
  function toolErrorTextToString(errorText) {
34872
34878
  return errorText == null ? "" : stringifyToolResult(errorText);
34873
34879
  }
34880
+ /**
34881
+ * Serializes with `JSON.stringify` itself, the serializer storage uses, so a count of this text describes what
34882
+ * storage holds and a reload reads back (`toJSON()`, boxed primitives, class instances, array indices).
34883
+ */
34874
34884
  function stringifyToolResult(value) {
34875
34885
  if (typeof value === "string") return value;
34876
- const sanitized = sanitizeToolResultValue(value);
34886
+ let json;
34877
34887
  try {
34878
- return JSON.stringify(sanitized, null, 2);
34888
+ json = JSON.stringify(value, redactEncryptedContent, 2);
34879
34889
  } catch {
34880
- return String(sanitized);
34890
+ return String(value);
34881
34891
  }
34892
+ if (json === void 0) return "";
34893
+ return json.startsWith("\"") ? JSON.parse(json) : json;
34882
34894
  }
34883
34895
  function resolveToolResultValue(part, invocationResult) {
34884
34896
  const mastraMetadata = part?.providerMetadata?.mastra;
@@ -34892,13 +34904,58 @@ function resolveToolResultValue(part, invocationResult) {
34892
34904
  usingStoredModelOutput: false
34893
34905
  };
34894
34906
  }
34907
+ const PREFIX_CHUNK_MIN_LENGTH = 256;
34908
+ function isAsciiAlphanumeric(code) {
34909
+ return code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122;
34910
+ }
34911
+ function isSplitWhitespace(code) {
34912
+ return code === 32 || code === 10 || code === 9 || code === 13;
34913
+ }
34914
+ /**
34915
+ * Returns a function that counts `estimateTokenCount(text.slice(0, end) + suffix)` without rescanning the
34916
+ * whole prefix on every call.
34917
+ *
34918
+ * tokenx splits text into segments on whitespace and punctuation runs and sums a per-segment estimate.
34919
+ * Letters and digits are never separators and whitespace always is, so the position between an ASCII
34920
+ * letter or digit and a following whitespace character is always a segment boundary: the count of any
34921
+ * string that shares the text up to such a position equals the count before it plus the count after it.
34922
+ * The text is cut at those boundaries once, and each call only rescans the chunk it ends in.
34923
+ */
34924
+ function createPrefixTokenCounter(text) {
34925
+ const boundaries = [0];
34926
+ const tokensBefore = [0];
34927
+ let chunkStart = 0;
34928
+ let runningTokens = 0;
34929
+ 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))) {
34930
+ runningTokens += estimateTokenCount(text.slice(chunkStart, i));
34931
+ boundaries.push(i);
34932
+ tokensBefore.push(runningTokens);
34933
+ chunkStart = i;
34934
+ }
34935
+ return (end, suffix = "") => {
34936
+ let low = 0;
34937
+ let high = boundaries.length - 1;
34938
+ while (low < high) {
34939
+ const mid = low + high + 1 >> 1;
34940
+ if (boundaries[mid] <= end) low = mid;
34941
+ else high = mid - 1;
34942
+ }
34943
+ return tokensBefore[low] + estimateTokenCount(text.slice(boundaries[low], end) + suffix);
34944
+ };
34945
+ }
34895
34946
  function truncateStringByTokens(text, maxTokens) {
34896
34947
  if (!text || maxTokens <= 0) return "";
34897
- const totalTokens = estimateTokenCount(text);
34948
+ const countPrefixTokens = createPrefixTokenCounter(text);
34949
+ const totalTokens = countPrefixTokens(text.length);
34898
34950
  if (totalTokens <= maxTokens) return text;
34899
34951
  const buildCandidate = (sliceEnd) => {
34900
- const visible = safeSlice(text, sliceEnd);
34901
- return `${visible}\n... [truncated ~${totalTokens - estimateTokenCount(visible)} tokens]`;
34952
+ const visibleEnd = safeSlice(text, sliceEnd).length;
34953
+ const suffix = `\n... [truncated ~${totalTokens - countPrefixTokens(visibleEnd)} tokens]`;
34954
+ return {
34955
+ visibleEnd,
34956
+ suffix,
34957
+ tokens: countPrefixTokens(visibleEnd, suffix)
34958
+ };
34902
34959
  };
34903
34960
  let low = 0;
34904
34961
  let high = text.length;
@@ -34906,12 +34963,12 @@ function truncateStringByTokens(text, maxTokens) {
34906
34963
  while (low <= high) {
34907
34964
  const mid = Math.floor((low + high) / 2);
34908
34965
  const candidate = buildCandidate(mid);
34909
- if (estimateTokenCount(candidate) <= maxTokens) {
34966
+ if (candidate.tokens <= maxTokens) {
34910
34967
  best = candidate;
34911
34968
  low = mid + 1;
34912
34969
  } else high = mid - 1;
34913
34970
  }
34914
- return best;
34971
+ return text.slice(0, best.visibleEnd) + best.suffix;
34915
34972
  }
34916
34973
  function formatToolResultForObserver(value, options) {
34917
34974
  return truncateStringByTokens(stringifyToolResult(value), options?.maxTokens ?? 5e3);
@@ -37127,9 +37184,24 @@ function mergeCacheEntry(cache, key, entry) {
37127
37184
  function getPartCacheEntry(part, key) {
37128
37185
  return getCacheEntry(getPartMastraMetadata(part)?.tokenEstimate, key);
37129
37186
  }
37187
+ /**
37188
+ * Parts this process gave a new stored count. A part loaded from storage with its count is never in here,
37189
+ * so a message holding one of these parts has a count storage does not have yet.
37190
+ */
37191
+ const partsWithUnsavedCount = /* @__PURE__ */ new WeakSet();
37192
+ /** Whether `part` gained a stored count in this process that has not been handed to a save yet. */
37193
+ function hasUnsavedTokenEstimate(part) {
37194
+ return typeof part === "object" && part !== null && partsWithUnsavedCount.has(part);
37195
+ }
37196
+ /** Note that `part`'s count is on its way to storage, so later steps do not save it again. */
37197
+ function markTokenEstimateSaved(part) {
37198
+ if (typeof part === "object" && part !== null) partsWithUnsavedCount.delete(part);
37199
+ }
37200
+ const partCountMemo = /* @__PURE__ */ new WeakMap();
37130
37201
  function setPartCacheEntry(part, key, entry) {
37131
37202
  const mastraMetadata = ensurePartMastraMetadata(part);
37132
37203
  mastraMetadata.tokenEstimate = mergeCacheEntry(mastraMetadata.tokenEstimate, key, entry);
37204
+ partsWithUnsavedCount.add(part);
37133
37205
  }
37134
37206
  /**
37135
37207
  * Extracts a caller-supplied token estimate stamped on a part via
@@ -37288,7 +37360,7 @@ async function resolveImageDimensionsAsync(part) {
37288
37360
  const url = resolveHttpAssetUrl(getObjectValue(part, "image") ?? getObjectValue(part, "data"));
37289
37361
  if (!url) return existing;
37290
37362
  try {
37291
- const probeImageSize = (await import("./probe-image-size-DZvSdjzK.js").then((m) => /* @__PURE__ */ __toESM$1(m.default, 1))).default;
37363
+ const probeImageSize = (await import("./probe-image-size-zXQBlFaQ.js").then((m) => /* @__PURE__ */ __toESM$1(m.default, 1))).default;
37292
37364
  const probed = await probeImageSize(url, {
37293
37365
  open_timeout: REMOTE_IMAGE_PROBE_TIMEOUT_MS,
37294
37366
  response_timeout: REMOTE_IMAGE_PROBE_TIMEOUT_MS,
@@ -37823,14 +37895,19 @@ async function fetchGoogleAttachmentTokenEstimate(modelId, part) {
37823
37895
  * undercounted as generic JSON blobs.
37824
37896
  */
37825
37897
  var TokenCounter = class TokenCounter {
37826
- cacheSource;
37898
+ /**
37899
+ * Stored counts belong to the stock estimator. A subclass or instance that overrides `countString`
37900
+ * reads and writes its own namespace, so it never reuses a count the stock estimator saved.
37901
+ */
37902
+ get cacheSource() {
37903
+ return this.countString === TokenCounter.prototype.countString ? `v${TOKEN_ESTIMATE_CACHE_VERSION}:${resolveEstimatorId()}` : `v${TOKEN_ESTIMATE_CACHE_VERSION}:custom`;
37904
+ }
37827
37905
  defaultModelContext;
37828
37906
  inFlightAttachmentCounts = /* @__PURE__ */ new Map();
37829
37907
  multimodalToolResultCounts = /* @__PURE__ */ new WeakMap();
37830
37908
  static TOKENS_PER_MESSAGE = 3.8;
37831
37909
  static TOKENS_PER_CONVERSATION = 24;
37832
37910
  constructor(options) {
37833
- this.cacheSource = `v${TOKEN_ESTIMATE_CACHE_VERSION}:${resolveEstimatorId()}`;
37834
37911
  this.defaultModelContext = parseModelContext(options?.model);
37835
37912
  }
37836
37913
  runWithModelContext(model, fn) {
@@ -37861,6 +37938,28 @@ var TokenCounter = class TokenCounter {
37861
37938
  });
37862
37939
  return tokens;
37863
37940
  }
37941
+ /**
37942
+ * Count one content-only piece of a part (its text, a tool's args or result) the same way as
37943
+ * {@link readOrPersistPartEstimate}: a stored count is reused only when its content hash matches.
37944
+ * `refs` are the values the payload is built from. While the same part object still holds the same
37945
+ * refs, the count from the last call is returned without serializing or hashing again, so a part
37946
+ * counted by `getStatus` and then by the next step is hashed once per process.
37947
+ * Only string refs are memoized (object payloads are hashed every time, since they can change in place).
37948
+ */
37949
+ readOrPersistMemoizedPartEstimate(part, kind, refs, getPayload) {
37950
+ if (!refs.every((ref) => typeof ref === "string")) return this.readOrPersistPartEstimate(part, kind, getPayload());
37951
+ let byKind = partCountMemo.get(part);
37952
+ const memo = byKind?.get(kind);
37953
+ if (memo && memo.owner === this && memo.refs.length === refs.length && memo.refs.every((ref, i) => ref === refs[i])) return memo.tokens;
37954
+ const tokens = this.readOrPersistPartEstimate(part, kind, getPayload());
37955
+ if (!byKind) partCountMemo.set(part, byKind = /* @__PURE__ */ new Map());
37956
+ byKind.set(kind, {
37957
+ owner: this,
37958
+ refs,
37959
+ tokens
37960
+ });
37961
+ return tokens;
37962
+ }
37864
37963
  readOrPersistFixedPartEstimate(part, kind, payload, tokens) {
37865
37964
  const key = buildEstimateKey(kind, payload);
37866
37965
  const cached = getPartCacheEntry(part, key);
@@ -38211,18 +38310,23 @@ var TokenCounter = class TokenCounter {
38211
38310
  /**
38212
38311
  * Count the name and the arguments of a tool call. Every state before the tool produces an
38213
38312
  * output holds the same call signature in the context window, so all of those states share
38214
- * these cache kinds. `buildEstimateKey` hashes the text, so a shared kind stays correct and
38215
- * keeps the estimate warm while the invocation moves from one state to the next.
38313
+ * these cache kinds, and the estimate stays warm while the invocation moves from one state to
38314
+ * the next. Name and args don't change across those states once the call stops streaming.
38216
38315
  */
38217
38316
  countToolCallSignature(part, invocation) {
38218
38317
  let tokens = 0;
38219
38318
  let overheadDelta = 0;
38220
- if (invocation.toolName) tokens += this.readOrPersistPartEstimate(part, "tool-call-name", invocation.toolName);
38319
+ const storable = invocation.state !== "partial-call";
38320
+ const count = (kind, ref, getPayload) => storable ? this.readOrPersistMemoizedPartEstimate(part, kind, [ref], getPayload) : this.readOrPersistPartEstimate(part, kind, getPayload());
38321
+ if (invocation.toolName) {
38322
+ const toolName = invocation.toolName;
38323
+ tokens += count("tool-call-name", toolName, () => toolName);
38324
+ }
38221
38325
  if (invocation.args !== void 0) {
38222
- if (typeof invocation.args === "string") tokens += this.readOrPersistPartEstimate(part, "tool-call-args", invocation.args);
38326
+ const args = invocation.args;
38327
+ if (typeof args === "string") tokens += count("tool-call-args", args, () => args);
38223
38328
  else {
38224
- const argsJson = JSON.stringify(invocation.args);
38225
- tokens += this.readOrPersistPartEstimate(part, "tool-call-args-json", argsJson);
38329
+ tokens += count("tool-call-args-json", args, () => JSON.stringify(args));
38226
38330
  overheadDelta -= 12;
38227
38331
  }
38228
38332
  }
@@ -38234,11 +38338,14 @@ var TokenCounter = class TokenCounter {
38234
38338
  countNonAttachmentPart(part) {
38235
38339
  let overheadDelta = 0;
38236
38340
  let extraMessageDelta = 0;
38237
- if (part.type === "text") return {
38238
- tokens: this.readOrPersistPartEstimate(part, "text", part.text),
38239
- overheadDelta,
38240
- extraMessageDelta
38241
- };
38341
+ if (part.type === "text") {
38342
+ const text = part.text;
38343
+ return {
38344
+ tokens: this.readOrPersistMemoizedPartEstimate(part, "text", [text], () => text),
38345
+ overheadDelta,
38346
+ extraMessageDelta
38347
+ };
38348
+ }
38242
38349
  if (part.type === "tool-invocation") {
38243
38350
  const invocation = part.toolInvocation;
38244
38351
  const state = invocation.state;
@@ -38257,7 +38364,7 @@ var TokenCounter = class TokenCounter {
38257
38364
  tokens += signature.tokens;
38258
38365
  overheadDelta += signature.overheadDelta;
38259
38366
  const reason = invocation.approval?.reason;
38260
- if (reason) tokens += this.readOrPersistPartEstimate(part, "tool-approval-reason", reason);
38367
+ if (reason) tokens += this.readOrPersistMemoizedPartEstimate(part, "tool-approval-reason", [reason], () => reason);
38261
38368
  return {
38262
38369
  tokens,
38263
38370
  overheadDelta,
@@ -38273,15 +38380,12 @@ var TokenCounter = class TokenCounter {
38273
38380
  if (resultForCounting !== void 0 && (typeof resultForCounting !== "string" || resultForCounting.trim().length > 0)) {
38274
38381
  const contentTokens = this.countMultimodalToolResultContent(part, resultForCounting);
38275
38382
  if (contentTokens !== void 0) tokens += contentTokens;
38276
- else {
38277
- const formattedResult = serializeToolResultForTokenCounting(resultForCounting);
38278
- tokens += this.readOrPersistPartEstimate(part, usingStoredModelOutput ? "tool-result-model-output-json" : "tool-result-json", formattedResult);
38279
- }
38383
+ else tokens += this.readOrPersistMemoizedPartEstimate(part, usingStoredModelOutput ? "tool-result-model-output-json" : "tool-result-json", [resultForCounting], () => serializeToolResultForTokenCounting(resultForCounting));
38280
38384
  if (typeof resultForCounting !== "string") overheadDelta -= 12;
38281
38385
  } else {
38282
38386
  const errorText = toolErrorTextToString(invocation.errorText);
38283
38387
  const fallback = invocation.isError ? errorText.trim() ? errorText : "Tool execution failed" : "[empty result]";
38284
- tokens += this.readOrPersistPartEstimate(part, invocation.isError ? "tool-result-error" : "tool-result-json", fallback);
38388
+ tokens += this.readOrPersistMemoizedPartEstimate(part, invocation.isError ? "tool-result-error" : "tool-result-json", [fallback], () => fallback);
38285
38389
  }
38286
38390
  return {
38287
38391
  tokens,
@@ -38295,7 +38399,7 @@ var TokenCounter = class TokenCounter {
38295
38399
  tokens += signature.tokens;
38296
38400
  overheadDelta += signature.overheadDelta;
38297
38401
  const reason = invocation.approval?.reason?.trim() ? invocation.approval.reason : "Tool call was not approved by the user";
38298
- tokens += this.readOrPersistPartEstimate(part, "tool-result-denied", reason);
38402
+ tokens += this.readOrPersistMemoizedPartEstimate(part, "tool-result-denied", [reason], () => reason);
38299
38403
  return {
38300
38404
  tokens,
38301
38405
  overheadDelta,
@@ -38309,7 +38413,7 @@ var TokenCounter = class TokenCounter {
38309
38413
  overheadDelta += signature.overheadDelta;
38310
38414
  const errorText = toolErrorTextToString(invocation.errorText);
38311
38415
  const errorMessage = errorText.trim() ? errorText : "Tool execution failed";
38312
- tokens += this.readOrPersistPartEstimate(part, "tool-result-error", errorMessage);
38416
+ tokens += this.readOrPersistMemoizedPartEstimate(part, "tool-result-error", [errorMessage], () => errorMessage);
38313
38417
  return {
38314
38418
  tokens,
38315
38419
  overheadDelta,
@@ -38322,6 +38426,11 @@ var TokenCounter = class TokenCounter {
38322
38426
  overheadDelta,
38323
38427
  extraMessageDelta
38324
38428
  };
38429
+ if (part.type === "step-start") return {
38430
+ tokens: 0,
38431
+ overheadDelta,
38432
+ extraMessageDelta
38433
+ };
38325
38434
  if (part.type === "reasoning") return {
38326
38435
  tokens: 0,
38327
38436
  overheadDelta,
@@ -41699,6 +41808,7 @@ const threadTitleInstructions = `A short, noun-phrase title for this conversatio
41699
41808
  - "Auth bug fix" \u2014 not "Fixing the auth bug"
41700
41809
  - "Dark mode toggle" \u2014 not "User wants dark mode toggle added"
41701
41810
  - "Deployment pipeline setup" \u2014 not "Setting up deployment pipeline for project"
41811
+ Write the title in the same language the user's messages are written in.
41702
41812
  Only update when the topic meaningfully changes.`;
41703
41813
  function createCurrentTaskExtractor() {
41704
41814
  return new Extractor({
@@ -43650,13 +43760,54 @@ ObservationStrategy.create = ((om, opts) => {
43650
43760
  if (deps.scope === "resource" && opts.resourceId) return new ResourceScopedObservationStrategy(deps, opts);
43651
43761
  return new SyncObservationStrategy(deps, opts);
43652
43762
  });
43763
+ /**
43764
+ * Mark the stored history of `threadId` in `messageList` that OM gave new token counts, so the counts are saved
43765
+ * with the messages. Call the returned function once the counting is done: every message holding a part that
43766
+ * gained a count in this process is marked for resave, and the normal save writes it back whole. Counts made
43767
+ * before this is called (while the turn loaded history) are caught too.
43768
+ *
43769
+ * Only messages of `threadId` are marked. A message recalled from another thread of the resource is counted but
43770
+ * never written, because saving it would bump that thread's `updatedAt` and reorder the recent-thread list.
43771
+ *
43772
+ * A Core without `markForResave` is left alone: counting still works, the counts are just not saved.
43773
+ */
43774
+ function resaveCountedMessagesFor(messageList, threadId) {
43775
+ if (typeof messageList.markForResave !== "function") return () => {};
43776
+ return () => {
43777
+ for (const message of messageList.get.remembered.db()) {
43778
+ if (message.threadId !== threadId) continue;
43779
+ const parts = message.content?.parts ?? [];
43780
+ if (!parts.some(hasUnsavedTokenEstimate)) continue;
43781
+ messageList.markForResave(message);
43782
+ parts.forEach(markTokenEstimateSaved);
43783
+ }
43784
+ };
43785
+ }
43786
+ /** The stored messages marked for resave in `messageList`; none for a Core without `markForResave`. */
43787
+ function messagesMarkedForResave(messageList) {
43788
+ return typeof messageList.getMessagesToResave === "function" ? messageList.getMessagesToResave() : [];
43789
+ }
43790
+ /**
43791
+ * Ids of the stored messages marked for resave in `messageList` that are not in `ownMessages` (the turn's
43792
+ * own input and output). Those are saved whole; the rest only gained counts and are patched onto storage.
43793
+ */
43794
+ function idsMarkedForResave(messageList, ownMessages = []) {
43795
+ const own = new Set(ownMessages.map((message) => message.id));
43796
+ return new Set(messagesMarkedForResave(messageList).map((message) => message.id).filter((id) => !own.has(id)));
43797
+ }
43798
+ /** `messages` with the messages marked for resave added, each message once. */
43799
+ function withMessagesMarkedForResave(messageList, messages) {
43800
+ const ids = new Set(messages.map((message) => message.id));
43801
+ return [...messages, ...messagesMarkedForResave(messageList).filter((message) => !ids.has(message.id))];
43802
+ }
43653
43803
  async function loadMemoryContextMessages({ memory, messageList, threadId, resourceId, runState }) {
43654
43804
  const ctx = await memory.getContext({
43655
43805
  threadId,
43656
43806
  resourceId,
43657
43807
  runState
43658
43808
  });
43659
- for (const msg of ctx.messages) if (msg.role !== "system") messageList.add(msg, "memory");
43809
+ const messages = ctx.messages.filter((msg) => msg.role !== "system");
43810
+ if (messages.length) messageList.add(messages, "memory");
43660
43811
  return ctx;
43661
43812
  }
43662
43813
  function hasPendingToolCall(message) {
@@ -43861,7 +44012,7 @@ var ObservationStep = class {
43861
44012
  const inputIds = new Set(messageList.get.input.db().map((msg) => msg.id));
43862
44013
  const sealedOutput = safeCandidates.filter((msg) => !inputIds.has(msg.id));
43863
44014
  messageList.removeByIds(sealedOutput.map((msg) => msg.id));
43864
- for (const msg of sealedOutput) messageList.add(msg, "memory");
44015
+ if (sealedOutput.length) messageList.add(sealedOutput, "memory");
43865
44016
  }
43866
44017
  if (!deferred) {
43867
44018
  om.trackBackgroundWork(om.buffer({
@@ -43910,7 +44061,7 @@ var ObservationStep = class {
43910
44061
  }).map((msg) => msg.id);
43911
44062
  inFlightIds = [...new Set(unreadIds)];
43912
44063
  if (messagesToSave.length > 0) {
43913
- for (const msg of messagesToSave) messageList.add(msg, "memory");
44064
+ messageList.add(messagesToSave, "memory");
43914
44065
  try {
43915
44066
  await om.persistMessages(messagesToSave, threadId, resourceId);
43916
44067
  } catch (error) {
@@ -44412,8 +44563,8 @@ var ObservationTurn = class {
44412
44563
  this._ended = true;
44413
44564
  const unsavedInput = messageList.get.input.db();
44414
44565
  const unsavedOutput = messageList.get.response.db();
44415
- const unsavedMessages = [...unsavedInput, ...unsavedOutput];
44416
- if (unsavedMessages.length > 0) await this.om.persistMessages(unsavedMessages, this.threadId, this.resourceId);
44566
+ const unsavedMessages = withMessagesMarkedForResave(messageList, [...unsavedInput, ...unsavedOutput]);
44567
+ if (unsavedMessages.length > 0) await this.om.persistMessages(unsavedMessages, this.threadId, this.resourceId, idsMarkedForResave(messageList, [...unsavedInput, ...unsavedOutput]));
44417
44568
  const asyncObservationEnabled = this.om.buffering.isAsyncObservationEnabled();
44418
44569
  const bufferOnIdle = this.om.getObservationConfig().bufferOnIdle;
44419
44570
  if (!this.abortSignal?.aborted && asyncObservationEnabled && bufferOnIdle) {
@@ -47317,18 +47468,86 @@ var ObservationalMemory = class ObservationalMemory {
47317
47468
  * to detect already-persisted messages, avoiding redundant DB operations.
47318
47469
  *
47319
47470
  * Messages with observation markers are always saved (upserted) even if sealed,
47320
- * because the markers need to be persisted to storage.
47471
+ * because the markers need to be persisted to storage. A stored message in `resaveIds` gained token
47472
+ * counts after it was stored, whether or not it is sealed: only those counts are copied onto the stored
47473
+ * 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
47474
+ * input or output, which are saved whole.
47321
47475
  */
47322
- async persistMessages(messagesToSave, threadId, resourceId) {
47476
+ async persistMessages(messagesToSave, threadId, resourceId, resaveIds) {
47323
47477
  const filteredMessages = [];
47324
- for (const msg of messagesToSave) if (!!(msg.content?.metadata)?.mastra?.sealed) {
47325
- if (findLastCompletedObservationBoundary(msg) !== -1) filteredMessages.push(msg);
47326
- } else filteredMessages.push(msg);
47478
+ const storedWithNewCounts = [];
47479
+ for (const msg of messagesToSave) {
47480
+ if (!!(msg.content?.metadata)?.mastra?.sealed && findLastCompletedObservationBoundary(msg) === -1 && !resaveIds?.has(msg.id)) continue;
47481
+ if (resaveIds?.has(msg.id) && findLastCompletedObservationBoundary(msg) === -1) storedWithNewCounts.push(msg);
47482
+ else filteredMessages.push(msg);
47483
+ }
47327
47484
  if (filteredMessages.length > 0) await this.messageHistory.persistMessages({
47328
47485
  messages: filteredMessages,
47329
47486
  threadId,
47330
47487
  resourceId
47331
47488
  });
47489
+ try {
47490
+ await this.persistTokenEstimatesOntoStored(storedWithNewCounts);
47491
+ } catch (error) {
47492
+ omError("[OM] Failed to save token counts for stored messages", error);
47493
+ }
47494
+ }
47495
+ /**
47496
+ * Copy the token counts of `messages` onto their stored copies. A stored copy can hold
47497
+ * parts the in-memory one lacks (markers written straight to storage), so it is patched
47498
+ * instead of saved whole. Each count goes to the first stored part whose content matches the counted
47499
+ * part, so a part that changed in storage keeps no count and is counted again on read.
47500
+ */
47501
+ async persistTokenEstimatesOntoStored(messages) {
47502
+ if (messages.length === 0) return;
47503
+ const contentOf = (part) => {
47504
+ const { tokenEstimate: _tokenEstimate, ...mastra } = part.providerMetadata?.mastra ?? {};
47505
+ return JSON.stringify({
47506
+ ...part,
47507
+ providerMetadata: {
47508
+ ...part.providerMetadata,
47509
+ mastra
47510
+ }
47511
+ });
47512
+ };
47513
+ const live = new Map(messages.map((message) => [message.id, message]));
47514
+ const { messages: stored } = await this.storage.listMessagesById({ messageIds: [...live.keys()] });
47515
+ const updates = [];
47516
+ for (const row of stored) {
47517
+ const counts = /* @__PURE__ */ new Map();
47518
+ for (const part of live.get(row.id)?.content.parts ?? []) {
47519
+ const tokenEstimate = part.providerMetadata?.mastra?.tokenEstimate;
47520
+ if (!tokenEstimate) continue;
47521
+ const key = contentOf(part);
47522
+ counts.set(key, [...counts.get(key) ?? [], tokenEstimate]);
47523
+ }
47524
+ if (counts.size === 0) continue;
47525
+ let changed = false;
47526
+ const parts = row.content.parts.map((part) => {
47527
+ const tokenEstimate = counts.get(contentOf(part))?.shift();
47528
+ if (!tokenEstimate) return part;
47529
+ changed = true;
47530
+ const providerMetadata = part.providerMetadata ?? {};
47531
+ return {
47532
+ ...part,
47533
+ providerMetadata: {
47534
+ ...providerMetadata,
47535
+ mastra: {
47536
+ ...providerMetadata.mastra,
47537
+ tokenEstimate
47538
+ }
47539
+ }
47540
+ };
47541
+ });
47542
+ if (changed) updates.push({
47543
+ id: row.id,
47544
+ content: {
47545
+ ...row.content,
47546
+ parts
47547
+ }
47548
+ });
47549
+ }
47550
+ if (updates.length > 0) await this.storage.updateMessages({ messages: updates });
47332
47551
  }
47333
47552
  /**
47334
47553
  * Load messages from storage that haven't been observed yet.
@@ -49129,11 +49348,12 @@ var ObservationalMemoryProcessor = class {
49129
49348
  state.__omTurn = void 0;
49130
49349
  if (!activeTurn || activeTurn.ended) return;
49131
49350
  const terminalList = messageList ?? activeTurn.messageList;
49132
- const unsavedMessages = [...terminalList.get.input.db(), ...terminalList.get.response.db()];
49351
+ const ownMessages = [...terminalList.get.input.db(), ...terminalList.get.response.db()];
49352
+ const unsavedMessages = withMessagesMarkedForResave(terminalList, ownMessages);
49133
49353
  try {
49134
49354
  await activeTurn.end(terminalList);
49135
49355
  } catch (error) {
49136
- if (unsavedMessages.length > 0) await this.engine.persistMessages(unsavedMessages, activeTurn.threadId, activeTurn.resourceId).catch(() => {});
49356
+ if (unsavedMessages.length > 0) await this.engine.persistMessages(unsavedMessages, activeTurn.threadId, activeTurn.resourceId, idsMarkedForResave(terminalList, ownMessages)).catch(() => {});
49137
49357
  throw error;
49138
49358
  }
49139
49359
  }
@@ -49275,6 +49495,7 @@ var ObservationalMemoryProcessor = class {
49275
49495
  this.turn.responseMessageId = responseMessageId;
49276
49496
  {
49277
49497
  const step = this.turn.step(stepNumber);
49498
+ const resaveCounted = resaveCountedMessagesFor(messageList, threadId);
49278
49499
  let ctx;
49279
49500
  try {
49280
49501
  ctx = await step.prepare();
@@ -49309,6 +49530,7 @@ var ObservationalMemoryProcessor = class {
49309
49530
  threadId,
49310
49531
  resourceId
49311
49532
  });
49533
+ resaveCounted();
49312
49534
  const finalTotalPending = ctx.status.pendingTokens;
49313
49535
  try {
49314
49536
  await runOMCommit(this.engine.buffering.getLockKey(threadId, resourceId), () => this.engine.getStorage().setPendingMessageTokens(turnRecord.id, finalTotalPending), { abortSignal });
@@ -49348,6 +49570,7 @@ var ObservationalMemoryProcessor = class {
49348
49570
  return this.engine.getTokenCounter().runWithModelContext(state.__omActorModelContext, async () => {
49349
49571
  if (parseMemoryRequestContext(requestContext)?.memoryConfig?.readOnly) return messageList;
49350
49572
  const persistenceMessageList = messageList.cloneForPersistence();
49573
+ this.engine.getTokenCounter().countMessages(persistenceMessageList.get.response.db());
49351
49574
  const turn = asLiveTurn(state.__omTurn) ?? this.turn;
49352
49575
  const liveTurn = turn && !turn.ended ? turn : void 0;
49353
49576
  if (liveTurn) await liveTurn.end(persistenceMessageList);
@@ -49355,8 +49578,9 @@ var ObservationalMemoryProcessor = class {
49355
49578
  state.__omTurn = void 0;
49356
49579
  if (!liveTurn) {
49357
49580
  const newOutput = persistenceMessageList.get.response.db();
49358
- const messagesToSave = [...persistenceMessageList.get.input.db(), ...newOutput];
49359
- if (messagesToSave.length > 0 && context.threadId) await this.engine.persistMessages(messagesToSave, context.threadId, context.resourceId);
49581
+ const ownMessages = [...persistenceMessageList.get.input.db(), ...newOutput];
49582
+ const messagesToSave = withMessagesMarkedForResave(persistenceMessageList, ownMessages);
49583
+ if (messagesToSave.length > 0 && context.threadId) await this.engine.persistMessages(messagesToSave, context.threadId, context.resourceId, idsMarkedForResave(persistenceMessageList, ownMessages));
49360
49584
  }
49361
49585
  return messageList;
49362
49586
  });
@@ -53069,7 +53293,7 @@ const createModelInstance = async (provider, modelId, version = "v2") => {
53069
53293
  try {
53070
53294
  const providerFn = version === `v1` ? { v1: {
53071
53295
  openai: async () => {
53072
- const { openai } = await import("./dist-Bz6gINFc.js");
53296
+ const { openai } = await import("./dist-BWVxgpEw.js");
53073
53297
  return openai(modelId);
53074
53298
  },
53075
53299
  anthropic: async () => {
@@ -3,7 +3,7 @@ name: mastra-server
3
3
  description: Documentation for @mastra/server. Use when working with @mastra/server APIs, configuration, or implementation.
4
4
  metadata:
5
5
  package: "@mastra/server"
6
- version: "1.86.0-alpha.8"
6
+ version: "1.86.0-alpha.9"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.86.0-alpha.8",
2
+ "version": "1.86.0-alpha.9",
3
3
  "package": "@mastra/server",
4
4
  "exports": {},
5
5
  "modules": {}