@mastra/memory 1.41.3-alpha.3 → 1.41.3-alpha.5

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.
@@ -24283,14 +24283,14 @@ function getRetrievalInstructions(scope = "resource", customInstructions, search
24283
24283
  The recall tool works across ALL of this user's conversation threads, not just the current one.
24284
24284
 
24285
24285
  - Use \`mode: "search"\` with a \`query\` to find relevant history, even when you already know the thread. Each result includes its thread ID, observation group ID, and source message range.
24286
- - Use \`mode: "messages"\` for original wording or details behind an observation — pass \`threadId\` to read another thread and a \`cursor\` from the source message range.
24286
+ - Use \`mode: "messages"\` for original wording or details behind an observation \u2014 pass \`threadId\` to read another thread and a \`cursor\` from the source message range.
24287
24287
  - Use \`mode: "threads"\` to list the user's threads (IDs, titles, dates) when you need to discover where something was discussed. Use \`before\`/\`after\` to narrow by date.
24288
24288
 
24289
- **If search results look irrelevant, do not give up.** Search only covers content that has been indexed — a short or recent conversation may exist in raw message history before any observation of it was created. When search returns nothing suitable but the user is clearly referring to a past conversation, call \`mode: "threads"\` to find candidate threads (titles and dates are strong clues), then read them with \`mode: "messages"\`. Use a useful hit as an entry point to the surrounding history rather than treating it as the whole answer.` : `### Choosing a mode
24289
+ **If search results look irrelevant, do not give up.** Search only covers content that has been indexed \u2014 a short or recent conversation may exist in raw message history before any observation of it was created. When search returns nothing suitable but the user is clearly referring to a past conversation, call \`mode: "threads"\` to find candidate threads (titles and dates are strong clues), then read them with \`mode: "messages"\`. Use a useful hit as an entry point to the surrounding history rather than treating it as the whole answer.` : `### Choosing a mode
24290
24290
  The recall tool works across ALL of this user's conversation threads, not just the current one.
24291
24291
 
24292
24292
  - Use \`mode: "threads"\` to list the user's threads (IDs, titles, dates) when you need to discover where something was discussed. Use \`before\`/\`after\` to narrow by date.
24293
- - Use \`mode: "messages"\` when you know the thread — pass \`threadId\` to read another thread, or a \`cursor\` from an observation-group range.
24293
+ - Use \`mode: "messages"\` when you know the thread \u2014 pass \`threadId\` to read another thread, or a \`cursor\` from an observation-group range.
24294
24294
 
24295
24295
  When the user refers to a past conversation you don't have a cursor for, call \`mode: "threads"\` to find candidate threads (titles and dates are strong clues), then read them with \`mode: "messages"\`. Raw history may exist for threads that have no observations yet.` : `### Choosing a mode
24296
24296
  The recall tool is limited to the current conversation thread.
@@ -24315,7 +24315,7 @@ When searches keep returning the same groups, often as already-in-context refere
24315
24315
  "Excerpt already in current context" marks a hit whose text an earlier search result already shows. "Group already in current context" marks a group that is already in your observations or whose source messages are still in the conversation. "Source range overlaps current context" marks a group whose source messages are still in the conversation. Search keeps these references and tries lower-ranked matches to fill the requested number of excerpts. This backfill is bounded: fewer excerpts do not mean history is exhausted. Use the evidence already present rather than repeating the same lookup. You can still ${pagingEnabled ? "page a referenced group" : "read a referenced group's source messages"} when you need all of it, or search again if that context is no longer available.
24316
24316
 
24317
24317
  If search still finds nothing useful, browse raw messages${isResource ? " or discover other threads" : " in this thread"} before concluding the information is unavailable. Raw history may exist for threads that have no observations yet.` : "";
24318
- const base = `## Recall — looking up source messages
24318
+ const base = `## Recall \u2014 looking up source messages
24319
24319
 
24320
24320
  Your memory contains observation groups with IDs and source message ranges, shown as \`## Group\` headings with \`_range: startId:endId\` or as \`<observation-group>\` tags. Use the **recall** tool to recover retained original observations and source messages.
24321
24321
 
@@ -24326,13 +24326,13 @@ Groups marked \`kind="reflection"\` (rendered as \`_kind: reflection_\`) are los
24326
24326
 
24327
24327
  ### When to use recall
24328
24328
  - The user asks you to **repeat, show, or reproduce** something from a past conversation
24329
- - The user asks for **exact content** — code, text, quotes, error messages, URLs, file paths, specific numbers
24329
+ - The user asks for **exact content** \u2014 code, text, quotes, error messages, URLs, file paths, specific numbers
24330
24330
  - Your observations mention something but your memory lacks the detail needed to fully answer (e.g. you know a blog post was shared but only have a summary of it)
24331
24331
  - You want to **verify or expand on** an observation before responding
24332
24332
  - The answer depends on historical dates, order, or duration: verify both event dates and that they refer to the events the user means. Distinguish a plan, an actual start, a later update, and a repeated mention instead of choosing a nearby date from a summary
24333
24333
  - An observation records something the assistant proposed, such as a schedule, date, or plan, and your observations don't show what the user decided. Read the raw messages around it to find the user's decision before treating the proposal as what happened
24334
24334
  - Relevant details are missing, ambiguous, or conflicting in the current observations${isResource ? `
24335
- - The user references another conversation that your observations don't cover — even if you have no observations yet, their other threads may contain it` : ""}
24335
+ - The user references another conversation that your observations don't cover \u2014 even if you have no observations yet, their other threads may contain it` : ""}
24336
24336
 
24337
24337
  **Default to using recall when the user references specific past content.** Your observations capture the gist, not the details. If there's any doubt whether your memory is complete enough, use recall.
24338
24338
 
@@ -24367,17 +24367,17 @@ Each range has the format \`startId:endId\` where both are message IDs separated
24367
24367
  In \`mode: "messages"\`, recall returns **low** detail by default: truncated text and tool names only. Each message shows its ID and each part has a positional index like \`[p0]\`, \`[p1]\`, etc.
24368
24368
 
24369
24369
  - Use \`detail: "high"\` to get full message content including tool arguments and results. This will only return the high detail version of a single message part at a time.
24370
- - Use \`partIndex\` with a cursor to fetch a single part at full detail — for example, to read one specific tool result or code block without loading every part.
24370
+ - Use \`partIndex\` with a cursor to fetch a single part at full detail \u2014 for example, to read one specific tool result or code block without loading every part.
24371
24371
 
24372
24372
  If the result says \`truncated: true\`, the output was cut to fit the token budget. You can paginate or use \`partIndex\` to target specific content. If a single part is itself too large, follow the returned \`nextCharOffset\` as described below.
24373
24373
 
24374
24374
  ### Following up on truncated parts
24375
24375
  Low-detail results may include truncation hints like:
24376
- \`[truncated — call recall cursor="..." partIndex=N detail="high" for full content]\`
24376
+ \`[truncated \u2014 call recall cursor="..." partIndex=N detail="high" for full content]\`
24377
24377
 
24378
24378
  **When you see these hints and need the full content, make the exact call described in the hint.** This is the normal workflow: first recall at low detail to scan, then drill into specific parts at high detail. Do not stop at the low-detail result if the user asked for exact content.
24379
24379
 
24380
- If a single part is larger than the token budget, the \`partIndex\` result is \`truncated: true\` and includes \`nextCharOffset\`. Repeat the same call with \`charOffset\` set to that exact value to read the next chunk from where the previous one ended. Keep following \`nextCharOffset\` until the result no longer includes it — the chunks together contain the full part. Retrying without \`charOffset\` returns the same prefix again.
24380
+ If a single part is larger than the token budget, the \`partIndex\` result is \`truncated: true\` and includes \`nextCharOffset\`. Repeat the same call with \`charOffset\` set to that exact value to read the next chunk from where the previous one ended. Keep following \`nextCharOffset\` until the result no longer includes it \u2014 the chunks together contain the full part. Retrying without \`charOffset\` returns the same prefix again.
24381
24381
 
24382
24382
  ### When recall is NOT needed
24383
24383
  - The user is asking for a high-level summary and your observations already cover it
@@ -24774,6 +24774,15 @@ function buildThreadMetadataFromExtractedValues(extractors, values) {
24774
24774
  async function applyExtractorHooks(opts) {
24775
24775
  const values = normalizeExtractedValues(opts.values) ?? {};
24776
24776
  const failures = [...opts.failures ?? []];
24777
+ let recentMessages;
24778
+ let recentMessagesResolved = false;
24779
+ const resolveRecentMessages = () => {
24780
+ if (!recentMessagesResolved) {
24781
+ recentMessages = typeof opts.recentMessages === "function" ? opts.recentMessages() : opts.recentMessages;
24782
+ recentMessagesResolved = true;
24783
+ }
24784
+ return recentMessages;
24785
+ };
24777
24786
  for (const extractor of opts.extractors) {
24778
24787
  const isHook = extractor.mode === "hook";
24779
24788
  const hasValue = Object.prototype.hasOwnProperty.call(values, extractor.slug);
@@ -24793,7 +24802,9 @@ async function applyExtractorHooks(opts) {
24793
24802
  previous: isHook ? void 0 : opts.previousValues?.[extractor.slug],
24794
24803
  current,
24795
24804
  rawObservations: opts.rawObservations,
24796
- recentMessages: opts.recentMessages,
24805
+ get recentMessages() {
24806
+ return resolveRecentMessages();
24807
+ },
24797
24808
  mainAgent: opts.mainAgent,
24798
24809
  memory: opts.memory,
24799
24810
  sendSignal: opts.sendSignal,
@@ -25039,6 +25050,17 @@ function isTransientLLMError(error) {
25039
25050
  return visit(error);
25040
25051
  }
25041
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
+ /**
25042
25064
  * Compute the backoff delay (ms) for the Nth retry (0-indexed).
25043
25065
  *
25044
25066
  * Exponential growth (`initialDelayMs * backoffFactor^attempt`) capped at
@@ -25122,7 +25144,8 @@ async function attemptWithIdleTimeout(fn, label, idleTimeoutMs, abortSignal) {
25122
25144
  /**
25123
25145
  * Run `fn` with retries on transient transport-class errors.
25124
25146
  *
25125
- * 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
25126
25149
  * immediately. User-initiated aborts are rethrown without delay.
25127
25150
  *
25128
25151
  * @internal
@@ -25138,7 +25161,7 @@ async function withRetry(fn, opts) {
25138
25161
  } catch (error) {
25139
25162
  if (abortSignal?.aborted) throw error;
25140
25163
  if (!(error instanceof OmModelCallTimeoutError) && hasAbortInChain(error)) throw error;
25141
- if (attempt >= maxRetries || !isTransientLLMError(error)) {
25164
+ if (attempt >= maxRetries || !isTransientLLMError(error) || isExhaustedAccountError(error)) {
25142
25165
  if (attempt > 0) omDebug(`[OM:retry:${label}] giving up after ${attempt} retry/retries: ${error instanceof Error ? error.message : String(error)}`);
25143
25166
  throw error;
25144
25167
  }
@@ -25552,7 +25575,7 @@ const YEAR = String.raw`(?:19|20|21)\d{2}(?!\d)`;
25552
25575
  const MERIDIEM = String.raw`(?:[AaPp]\.[Mm]\.|[AaPp][Mm]\b)`;
25553
25576
  const TIME = String.raw`(?:,?\s+(?:at\s+)?\d{1,2}:\d{2}(?:\s*${MERIDIEM})?|\s+at\s+\d{1,2}\s*${MERIDIEM})`;
25554
25577
  const QUALIFIER = String.raw`(?:(?:early|mid|late)[- ](?:to[- ](?:early|mid|late)[- ])?)`;
25555
- const RANGE_SEP = String.raw`(?:\s*[–—]\s*|\s*-\s*|\s+(?:to|through|until)\s+)`;
25578
+ const RANGE_SEP = String.raw`(?:\s*[\u2013\u2014]\s*|\s*-\s*|\s+(?:to|through|until)\s+)`;
25556
25579
  /**
25557
25580
  * Dates written into observation text that carry their own year, longest forms first:
25558
25581
  * "Mar 1 - Mar 18, 2025", "May 27-28, 2023", "January 10, 2024 at 3:00 PM",
@@ -25855,15 +25878,15 @@ const SHORT_TOKEN_THRESHOLD = 3;
25855
25878
  const KANA_CHARS_PER_TOKEN = 1.35;
25856
25879
  const DEFAULT_LANGUAGE_CONFIGS = [
25857
25880
  {
25858
- pattern: /[äöüßẞ]/i,
25881
+ pattern: /[\u00E4\u00F6\u00FC\u00DF\u1E9E]/i,
25859
25882
  averageCharsPerToken: 2.6
25860
25883
  },
25861
25884
  {
25862
- pattern: /[éèêëàâîïôûùüÿçœæáíóúñ]/i,
25885
+ pattern: /[\u00E9\u00E8\u00EA\u00EB\u00E0\u00E2\u00EE\u00EF\u00F4\u00FB\u00F9\u00FC\u00FF\u00E7\u0153\u00E6\u00E1\u00ED\u00F3\u00FA\u00F1]/i,
25863
25886
  averageCharsPerToken: 3
25864
25887
  },
25865
25888
  {
25866
- pattern: /[ąćęłńóśźżěščřžýůúďťň]/i,
25889
+ pattern: /[\u0105\u0107\u0119\u0142\u0144\u00F3\u015B\u017A\u017C\u011B\u0161\u010D\u0159\u017E\u00FD\u016F\u00FA\u010F\u0165\u0148]/i,
25867
25890
  averageCharsPerToken: 2.5
25868
25891
  },
25869
25892
  {
@@ -25940,7 +25963,7 @@ const OBSERVER_TOOL_ARGUMENT_MAX_DEPTH = 5;
25940
25963
  const OBSERVER_TOOL_ARGUMENT_MAX_ENTRIES_PER_CONTAINER = 20;
25941
25964
  const OBSERVER_TOOL_ARGUMENT_MAX_OUTLINE_ENTRIES = 100;
25942
25965
  const OBSERVER_TOOL_ARGUMENT_MAX_PATH_CHARS = 160;
25943
- function isObjectLike$1(value) {
25966
+ function isObjectLike(value) {
25944
25967
  return typeof value === "object" && value !== null;
25945
25968
  }
25946
25969
  function sanitizeSurrogates(value) {
@@ -25952,10 +25975,10 @@ function sanitizeSurrogates(value) {
25952
25975
  if (next >= 56320 && next <= 57343) {
25953
25976
  sanitized += value.charAt(index) + value.charAt(index + 1);
25954
25977
  index++;
25955
- } else sanitized += "�";
25978
+ } else sanitized += "\uFFFD";
25956
25979
  continue;
25957
25980
  }
25958
- sanitized += code >= 56320 && code <= 57343 ? "�" : value[index];
25981
+ sanitized += code >= 56320 && code <= 57343 ? "\uFFFD" : value[index];
25959
25982
  }
25960
25983
  return sanitized;
25961
25984
  }
@@ -25977,7 +26000,7 @@ function truncatePath(path) {
25977
26000
  const headLength = 50;
25978
26001
  const tailLength = 60;
25979
26002
  const omitted = path.length - headLength - tailLength;
25980
- return `${safeSlice(path, headLength)}…[${omitted} chars; ${stablePathDigest(path)}]…${safeTail(path, tailLength)}`;
26003
+ return `${safeSlice(path, headLength)}\u2026[${omitted} chars; ${stablePathDigest(path)}]\u2026${safeTail(path, tailLength)}`;
25981
26004
  }
25982
26005
  function formatPath(parent, key, isArray) {
25983
26006
  if (isArray) return truncatePath(`${parent}[${key}]`);
@@ -26086,7 +26109,7 @@ function selectOutlineEntries(entries, limits) {
26086
26109
  const rendered = joinEntries(selected, marker);
26087
26110
  if (fits(rendered, limits)) return rendered;
26088
26111
  if (fits(marker, limits)) return marker;
26089
- return fits("…", limits) ? "…" : "";
26112
+ return fits("\u2026", limits) ? "\u2026" : "";
26090
26113
  }
26091
26114
  function indentPreview(value) {
26092
26115
  return value.split("\n").map((line) => ` | ${line}`).join("\n");
@@ -26126,16 +26149,16 @@ function formatToolArgumentsForObserver(value, options) {
26126
26149
  maxCharacters: options?.maxCharacters ?? Number.POSITIVE_INFINITY
26127
26150
  };
26128
26151
  if (limits.maxTokens <= 0 || limits.maxCharacters <= 0) return "";
26129
- if (!isObjectLike$1(value)) {
26152
+ if (!isObjectLike(value)) {
26130
26153
  if (typeof value !== "string" || value.length <= OBSERVER_TOOL_ARGUMENT_INLINE_STRING_MAX_CHARS) {
26131
26154
  const primitive = formatPrimitive(value);
26132
- return fits(primitive, limits) ? primitive : fits("…", limits) ? "…" : "";
26155
+ return fits(primitive, limits) ? primitive : fits("\u2026", limits) ? "\u2026" : "";
26133
26156
  }
26134
26157
  const summary = `<string, ${value.length} characters; preview size-limited>`;
26135
26158
  const rendered = appendWithinBudget(summary, formatPreview("preview", value, limits, summary), limits);
26136
26159
  if (rendered) return rendered;
26137
26160
  if (fits(summary, limits)) return summary;
26138
- return fits("…", limits) ? "…" : "";
26161
+ return fits("\u2026", limits) ? "\u2026" : "";
26139
26162
  }
26140
26163
  const outline = [];
26141
26164
  const previews = [];
@@ -26205,7 +26228,7 @@ function formatToolArgumentsForObserver(value, options) {
26205
26228
  });
26206
26229
  continue;
26207
26230
  }
26208
- if (!isObjectLike$1(entryValue)) {
26231
+ if (!isObjectLike(entryValue)) {
26209
26232
  outline.push({
26210
26233
  text: `${path}: ${formatPrimitive(entryValue)}`,
26211
26234
  depth: current.depth,
@@ -26287,28 +26310,22 @@ function formatToolArgumentsForObserver(value, options) {
26287
26310
  // src/processors/observational-memory/tool-result-helpers.ts
26288
26311
  const ENCRYPTED_CONTENT_KEY = "encryptedContent";
26289
26312
  const ENCRYPTED_CONTENT_REDACTION_THRESHOLD = 256;
26290
- function isObjectLike(value) {
26291
- return typeof value === "object" && value !== null;
26292
- }
26293
- function sanitizeToolResultValue(value, seen = /* @__PURE__ */ new WeakMap()) {
26294
- if (!isObjectLike(value)) return value;
26295
- if (seen.has(value)) return seen.get(value);
26296
- if (Array.isArray(value)) {
26297
- const sanitizedArray = [];
26298
- seen.set(value, sanitizedArray);
26299
- for (const item of value) sanitizedArray.push(sanitizeToolResultValue(item, seen));
26300
- return sanitizedArray;
26301
- }
26302
- const sanitizedObject = {};
26303
- seen.set(value, sanitizedObject);
26304
- for (const [key, entry] of Object.entries(value)) {
26305
- if (key === ENCRYPTED_CONTENT_KEY && typeof entry === "string" && entry.length > ENCRYPTED_CONTENT_REDACTION_THRESHOLD) {
26306
- sanitizedObject[key] = `[stripped encryptedContent: ${entry.length} characters]`;
26307
- continue;
26308
- }
26309
- 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;
26310
26321
  }
26311
- 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;
26312
26329
  }
26313
26330
  /**
26314
26331
  * Serializes a tool result without truncating it.
@@ -26328,14 +26345,20 @@ function serializeToolResultForTokenCounting(value) {
26328
26345
  function toolErrorTextToString(errorText) {
26329
26346
  return errorText == null ? "" : stringifyToolResult(errorText);
26330
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
+ */
26331
26352
  function stringifyToolResult(value) {
26332
26353
  if (typeof value === "string") return value;
26333
- const sanitized = sanitizeToolResultValue(value);
26354
+ let json;
26334
26355
  try {
26335
- return JSON.stringify(sanitized, null, 2);
26356
+ json = JSON.stringify(value, redactEncryptedContent, 2);
26336
26357
  } catch {
26337
- return String(sanitized);
26358
+ return String(value);
26338
26359
  }
26360
+ if (json === void 0) return "";
26361
+ return json.startsWith("\"") ? JSON.parse(json) : json;
26339
26362
  }
26340
26363
  function resolveToolResultValue(part, invocationResult) {
26341
26364
  const mastraMetadata = part?.providerMetadata?.mastra;
@@ -26349,13 +26372,58 @@ function resolveToolResultValue(part, invocationResult) {
26349
26372
  usingStoredModelOutput: false
26350
26373
  };
26351
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
+ }
26352
26414
  function truncateStringByTokens(text, maxTokens) {
26353
26415
  if (!text || maxTokens <= 0) return "";
26354
- const totalTokens = estimateTokenCount(text);
26416
+ const countPrefixTokens = createPrefixTokenCounter(text);
26417
+ const totalTokens = countPrefixTokens(text.length);
26355
26418
  if (totalTokens <= maxTokens) return text;
26356
26419
  const buildCandidate = (sliceEnd) => {
26357
- const visible = safeSlice(text, sliceEnd);
26358
- 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
+ };
26359
26427
  };
26360
26428
  let low = 0;
26361
26429
  let high = text.length;
@@ -26363,12 +26431,12 @@ function truncateStringByTokens(text, maxTokens) {
26363
26431
  while (low <= high) {
26364
26432
  const mid = Math.floor((low + high) / 2);
26365
26433
  const candidate = buildCandidate(mid);
26366
- if (estimateTokenCount(candidate) <= maxTokens) {
26434
+ if (candidate.tokens <= maxTokens) {
26367
26435
  best = candidate;
26368
26436
  low = mid + 1;
26369
26437
  } else high = mid - 1;
26370
26438
  }
26371
- return best;
26439
+ return text.slice(0, best.visibleEnd) + best.suffix;
26372
26440
  }
26373
26441
  function formatToolResultForObserver(value, options) {
26374
26442
  return truncateStringByTokens(stringifyToolResult(value), options?.maxTokens ?? 5e3);
@@ -26381,24 +26449,24 @@ function formatToolResultForObserver(value, options) {
26381
26449
  const OBSERVER_EXTRACTION_INSTRUCTIONS = `CRITICAL: DISTINGUISH USER ASSERTIONS FROM QUESTIONS
26382
26450
 
26383
26451
  When the user TELLS you something about themselves, mark it as an assertion:
26384
- - "I have two kids" → 🔴 (14:30) User stated has two kids
26385
- - "I work at Acme Corp" → 🔴 (14:31) User stated works at Acme Corp
26386
- - "I graduated in 2019" → 🔴 (14:32) User stated graduated in 2019
26452
+ - "I have two kids" \u2192 \u{1F534} (14:30) User stated has two kids
26453
+ - "I work at Acme Corp" \u2192 \u{1F534} (14:31) User stated works at Acme Corp
26454
+ - "I graduated in 2019" \u2192 \u{1F534} (14:32) User stated graduated in 2019
26387
26455
 
26388
26456
  When the user ASKS about something, mark it as a question/request:
26389
- - "Can you help me with X?" → 🔴 (15:00) User asked help with X
26390
- - "What's the best way to do Y?" → 🔴 (15:01) User asked best way to do Y
26457
+ - "Can you help me with X?" \u2192 \u{1F534} (15:00) User asked help with X
26458
+ - "What's the best way to do Y?" \u2192 \u{1F534} (15:01) User asked best way to do Y
26391
26459
 
26392
26460
  Distinguish between QUESTIONS and STATEMENTS OF INTENT:
26393
- - "Can you recommend..." → Question (extract as "User asked...")
26394
- - "I'm looking forward to [doing X]" → Statement of intent (extract as "User stated they will [do X] (include estimated/actual date if mentioned)")
26395
- - "I need to [do X]" → Statement of intent (extract as "User stated they need to [do X] (again, add date if mentioned)")
26461
+ - "Can you recommend..." \u2192 Question (extract as "User asked...")
26462
+ - "I'm looking forward to [doing X]" \u2192 Statement of intent (extract as "User stated they will [do X] (include estimated/actual date if mentioned)")
26463
+ - "I need to [do X]" \u2192 Statement of intent (extract as "User stated they need to [do X] (again, add date if mentioned)")
26396
26464
 
26397
26465
  STATE CHANGES AND UPDATES:
26398
26466
  When a user indicates they are changing something, frame it as a state change that supersedes previous information:
26399
- - "I'm going to start doing X instead of Y" → "User will start doing X (changing from Y)"
26400
- - "I'm switching from A to B" → "User is switching from A to B"
26401
- - "I moved my stuff to the new place" → "User moved their stuff to the new place (no longer at previous location)"
26467
+ - "I'm going to start doing X instead of Y" \u2192 "User will start doing X (changing from Y)"
26468
+ - "I'm switching from A to B" \u2192 "User is switching from A to B"
26469
+ - "I moved my stuff to the new place" \u2192 "User moved their stuff to the new place (no longer at previous location)"
26402
26470
 
26403
26471
  If the new state contradicts or updates previous information, make that explicit:
26404
26472
  - BAD: "User plans to use the new method"
@@ -26489,11 +26557,11 @@ BAD: User got something.
26489
26557
  GOOD: User purchased / received / was given something. (be specific)
26490
26558
 
26491
26559
  Common clarifications:
26492
- - "getting" something regularly → "subscribed to" or "enrolled in"
26493
- - "getting" something once → "purchased" or "acquired"
26494
- - "got" → "purchased", "received as gift", "was given", "picked up"
26495
- - "signed up" → "enrolled in", "registered for", "subscribed to"
26496
- - "stopped getting" → "canceled", "unsubscribed from", "discontinued"
26560
+ - "getting" something regularly \u2192 "subscribed to" or "enrolled in"
26561
+ - "getting" something once \u2192 "purchased" or "acquired"
26562
+ - "got" \u2192 "purchased", "received as gift", "was given", "picked up"
26563
+ - "signed up" \u2192 "enrolled in", "registered for", "subscribed to"
26564
+ - "stopped getting" \u2192 "canceled", "unsubscribed from", "discontinued"
26497
26565
 
26498
26566
  When the assistant interprets or confirms the user's vague language, prefer the assistant's precise terminology.
26499
26567
 
@@ -26578,16 +26646,16 @@ AVOIDING REPETITIVE OBSERVATIONS:
26578
26646
  - Do NOT repeat the same observation across multiple turns if there is no new information.
26579
26647
  - When the agent performs repeated similar actions (e.g., browsing files, running the same tool type multiple times), group them into a single parent observation with sub-bullets for each new result.
26580
26648
 
26581
- Example — BAD (repetitive):
26582
- * 🟡 (14:30) Agent used view tool on src/auth.ts
26583
- * 🟡 (14:31) Agent used view tool on src/users.ts
26584
- * 🟡 (14:32) Agent used view tool on src/routes.ts
26649
+ Example \u2014 BAD (repetitive):
26650
+ * \u{1F7E1} (14:30) Agent used view tool on src/auth.ts
26651
+ * \u{1F7E1} (14:31) Agent used view tool on src/users.ts
26652
+ * \u{1F7E1} (14:32) Agent used view tool on src/routes.ts
26585
26653
 
26586
- Example — GOOD (grouped):
26587
- * 🟡 (14:30) Agent browsed source files for auth flow
26588
- * -> viewed src/auth.ts — found token validation logic
26589
- * -> viewed src/users.ts — found user lookup by email
26590
- * -> viewed src/routes.ts — found middleware chain
26654
+ Example \u2014 GOOD (grouped):
26655
+ * \u{1F7E1} (14:30) Agent browsed source files for auth flow
26656
+ * -> viewed src/auth.ts \u2014 found token validation logic
26657
+ * -> viewed src/users.ts \u2014 found user lookup by email
26658
+ * -> viewed src/routes.ts \u2014 found middleware chain
26591
26659
 
26592
26660
  Only add a new observation for a repeated action if the NEW result changes the picture.
26593
26661
 
@@ -26600,29 +26668,29 @@ COMPLETION TRACKING:
26600
26668
  Completion observations are not just summaries. They are explicit memory signals to the assistant that a task, question, or subtask has been resolved.
26601
26669
  Without clear completion markers, the assistant may forget that work is already finished and may repeat, reopen, or continue an already-completed task.
26602
26670
 
26603
- Use ✅ to answer: "What exactly is now done?"
26671
+ Use \u2705 to answer: "What exactly is now done?"
26604
26672
  Choose completion observations that help the assistant know what is finished and should not be reworked unless new information appears.
26605
26673
 
26606
- Use ✅ when:
26674
+ Use \u2705 when:
26607
26675
  - The user explicitly confirms something worked or was answered ("thanks, that fixed it", "got it", "perfect")
26608
26676
  - The assistant provided a definitive, complete answer to a factual question and the user moved on
26609
26677
  - A multi-step task reached its stated goal
26610
26678
  - The user acknowledged receipt of requested information
26611
26679
  - A concrete subtask, fix, deliverable, or implementation step became complete during ongoing work
26612
26680
 
26613
- Do NOT use ✅ when:
26614
- - The assistant merely responded — the user might follow up with corrections
26681
+ Do NOT use \u2705 when:
26682
+ - The assistant merely responded \u2014 the user might follow up with corrections
26615
26683
  - The topic is paused but not resolved ("I'll try that later")
26616
26684
  - The user's reaction is ambiguous
26617
26685
 
26618
26686
  FORMAT:
26619
26687
  As a sub-bullet under the related observation group:
26620
- * 🔴 (14:30) User asked how to configure auth middleware
26688
+ * \u{1F534} (14:30) User asked how to configure auth middleware
26621
26689
  * -> Agent explained JWT setup with code example
26622
- * ✅ User confirmed auth is working
26690
+ * \u2705 User confirmed auth is working
26623
26691
 
26624
26692
  Or as a standalone observation when closing out a broader task:
26625
- * ✅ (14:45) Auth configuration task completed — user confirmed middleware is working
26693
+ * \u2705 (14:45) Auth configuration task completed \u2014 user confirmed middleware is working
26626
26694
 
26627
26695
  Completion observations should be terse but specific about WHAT was completed.
26628
26696
  Prefer concrete resolved outcomes over abstract workflow status so the assistant remembers what is already done.`;
@@ -26639,28 +26707,28 @@ buildObserverOutputFormat();
26639
26707
  */
26640
26708
  function buildObserverOutputFormat(extractors) {
26641
26709
  return `Use priority levels:
26642
- - 🔴 High: explicit user facts, preferences, unresolved goals, critical context
26643
- - 🟡 Medium: project details, learned information, tool results
26644
- - 🟢 Low: minor details, uncertain observations
26645
- - ✅ Completed: concrete task finished, question answered, issue resolved, goal achieved, or subtask completed in a way that helps the assistant know it is done
26710
+ - \u{1F534} High: explicit user facts, preferences, unresolved goals, critical context
26711
+ - \u{1F7E1} Medium: project details, learned information, tool results
26712
+ - \u{1F7E2} Low: minor details, uncertain observations
26713
+ - \u2705 Completed: concrete task finished, question answered, issue resolved, goal achieved, or subtask completed in a way that helps the assistant know it is done
26646
26714
 
26647
26715
  Group related observations (like tool sequences) by indenting:
26648
- * 🔴 (14:33) Agent debugging auth issue
26716
+ * \u{1F534} (14:33) Agent debugging auth issue
26649
26717
  * -> ran git status, found 3 modified files
26650
26718
  * -> viewed auth.ts:45-60, found missing null check
26651
26719
  * -> applied fix, tests now pass
26652
- * ✅ Tests passing, auth issue resolved
26720
+ * \u2705 Tests passing, auth issue resolved
26653
26721
 
26654
26722
  Group observations by date. Within a date, list observations in the order the events happened (not by importance), each with 24-hour time.
26655
26723
 
26656
26724
  <observations>
26657
26725
  Date: Dec 4, 2025
26658
- * 🔴 (14:30) User prefers direct answers
26659
- * 🔴 (14:31) Working on feature X
26660
- * 🟡 (14:32) User might prefer dark mode
26726
+ * \u{1F534} (14:30) User prefers direct answers
26727
+ * \u{1F534} (14:31) Working on feature X
26728
+ * \u{1F7E1} (14:32) User might prefer dark mode
26661
26729
 
26662
26730
  Date: Dec 5, 2025
26663
- * 🔴 (09:15) Continued work on feature X
26731
+ * \u{1F534} (09:15) Continued work on feature X
26664
26732
  </observations>
26665
26733
 
26666
26734
  ${buildExtractorOutputSections(extractors ?? []) || (extractors === void 0 ? `
@@ -26690,9 +26758,9 @@ const OBSERVER_GUIDELINES = `- Be specific enough for the assistant to act on
26690
26758
  - If the agent calls tools, observe what was called, why, and what was learned
26691
26759
  - When observing files with line numbers, include the line number if useful
26692
26760
  - If the agent provides a detailed response, observe the contents so it could be repeated
26693
- - Make sure you start each observation with a priority emoji (🔴, 🟡, 🟢) or a completion marker (✅)
26694
- - Capture the user's words closely — short/medium messages near-verbatim, long messages summarized with key quotes. User confirmations or explicit resolved outcomes should be ✅ when they clearly signal something is done; unresolved or critical user facts remain 🔴
26695
- - Treat ✅ as a memory signal that tells the assistant something is finished and should not be repeated unless new information changes it
26761
+ - Make sure you start each observation with a priority emoji (\u{1F534}, \u{1F7E1}, \u{1F7E2}) or a completion marker (\u2705)
26762
+ - Capture the user's words closely \u2014 short/medium messages near-verbatim, long messages summarized with key quotes. User confirmations or explicit resolved outcomes should be \u2705 when they clearly signal something is done; unresolved or critical user facts remain \u{1F534}
26763
+ - Treat \u2705 as a memory signal that tells the assistant something is finished and should not be repeated unless new information changes it
26696
26764
  - Make completion observations answer "What exactly is now done?"
26697
26765
  - Prefer concrete resolved outcomes over meta-level workflow or bookkeeping updates
26698
26766
  - When multiple concrete things were completed, capture the concrete completed work rather than collapsing it into a vague progress summary
@@ -26746,8 +26814,8 @@ For multi-thread output, wrap each thread's observations like this:
26746
26814
  <observations>
26747
26815
  <thread id="thread_id_1">
26748
26816
  Date: Dec 4, 2025
26749
- * 🔴 (14:30) User prefers direct answers
26750
- * 🔴 (14:31) Working on feature X${currentTaskEnabled ? `
26817
+ * \u{1F534} (14:30) User prefers direct answers
26818
+ * \u{1F534} (14:31) Working on feature X${currentTaskEnabled ? `
26751
26819
 
26752
26820
  <current-task>
26753
26821
  What the agent is currently working on in this thread
@@ -26760,7 +26828,7 @@ Hint for the agent's next message in this thread
26760
26828
 
26761
26829
  <thread id="thread_id_2">
26762
26830
  Date: Dec 5, 2025
26763
- * 🔴 (09:15) User asked about deployment${currentTaskEnabled ? `
26831
+ * \u{1F534} (09:15) User asked about deployment${currentTaskEnabled ? `
26764
26832
 
26765
26833
  <current-task>
26766
26834
  Current task for this thread
@@ -27608,7 +27676,7 @@ function sanitizeObservationLines(observations) {
27608
27676
  const lines = observations.split("\n");
27609
27677
  let changed = false;
27610
27678
  for (let i = 0; i < lines.length; i++) if (lines[i].length > MAX_OBSERVATION_LINE_CHARS) {
27611
- lines[i] = safeSlice(lines[i], MAX_OBSERVATION_LINE_CHARS) + " … [truncated]";
27679
+ lines[i] = safeSlice(lines[i], MAX_OBSERVATION_LINE_CHARS) + " \u2026 [truncated]";
27612
27680
  changed = true;
27613
27681
  }
27614
27682
  return changed ? lines.join("\n") : observations;
@@ -27832,8 +27900,8 @@ function extractCurrentTask(observations) {
27832
27900
  */
27833
27901
  function optimizeObservationsForContext(observations) {
27834
27902
  let optimized = stripEphemeralAnchorIds(observations);
27835
- optimized = optimized.replace(/🟡\s*/g, "");
27836
- optimized = optimized.replace(/🟢\s*/g, "");
27903
+ optimized = optimized.replace(/\uD83D\uDFE1\s*/g, "");
27904
+ optimized = optimized.replace(/\uD83D\uDFE2\s*/g, "");
27837
27905
  optimized = optimized.replace(/\s*->\s*/g, " ");
27838
27906
  optimized = optimized.replace(/ +/g, " ");
27839
27907
  optimized = optimized.replace(/\n{3,}/g, "\n\n");
@@ -28634,9 +28702,24 @@ function mergeCacheEntry(cache, key, entry) {
28634
28702
  function getPartCacheEntry(part, key) {
28635
28703
  return getCacheEntry(getPartMastraMetadata(part)?.tokenEstimate, key);
28636
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();
28637
28719
  function setPartCacheEntry(part, key, entry) {
28638
28720
  const mastraMetadata = ensurePartMastraMetadata(part);
28639
28721
  mastraMetadata.tokenEstimate = mergeCacheEntry(mastraMetadata.tokenEstimate, key, entry);
28722
+ partsWithUnsavedCount.add(part);
28640
28723
  }
28641
28724
  /**
28642
28725
  * Extracts a caller-supplied token estimate stamped on a part via
@@ -29330,14 +29413,19 @@ async function fetchGoogleAttachmentTokenEstimate(modelId, part) {
29330
29413
  * undercounted as generic JSON blobs.
29331
29414
  */
29332
29415
  var TokenCounter = class TokenCounter {
29333
- 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
+ }
29334
29423
  defaultModelContext;
29335
29424
  inFlightAttachmentCounts = /* @__PURE__ */ new Map();
29336
29425
  multimodalToolResultCounts = /* @__PURE__ */ new WeakMap();
29337
29426
  static TOKENS_PER_MESSAGE = 3.8;
29338
29427
  static TOKENS_PER_CONVERSATION = 24;
29339
29428
  constructor(options) {
29340
- this.cacheSource = `v${TOKEN_ESTIMATE_CACHE_VERSION}:${resolveEstimatorId()}`;
29341
29429
  this.defaultModelContext = parseModelContext(options?.model);
29342
29430
  }
29343
29431
  runWithModelContext(model, fn) {
@@ -29368,6 +29456,28 @@ var TokenCounter = class TokenCounter {
29368
29456
  });
29369
29457
  return tokens;
29370
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
+ }
29371
29481
  readOrPersistFixedPartEstimate(part, kind, payload, tokens) {
29372
29482
  const key = buildEstimateKey(kind, payload);
29373
29483
  const cached = getPartCacheEntry(part, key);
@@ -29718,18 +29828,23 @@ var TokenCounter = class TokenCounter {
29718
29828
  /**
29719
29829
  * Count the name and the arguments of a tool call. Every state before the tool produces an
29720
29830
  * output holds the same call signature in the context window, so all of those states share
29721
- * these cache kinds. `buildEstimateKey` hashes the text, so a shared kind stays correct and
29722
- * 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.
29723
29833
  */
29724
29834
  countToolCallSignature(part, invocation) {
29725
29835
  let tokens = 0;
29726
29836
  let overheadDelta = 0;
29727
- 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
+ }
29728
29843
  if (invocation.args !== void 0) {
29729
- 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);
29730
29846
  else {
29731
- const argsJson = JSON.stringify(invocation.args);
29732
- tokens += this.readOrPersistPartEstimate(part, "tool-call-args-json", argsJson);
29847
+ tokens += count("tool-call-args-json", args, () => JSON.stringify(args));
29733
29848
  overheadDelta -= 12;
29734
29849
  }
29735
29850
  }
@@ -29741,11 +29856,14 @@ var TokenCounter = class TokenCounter {
29741
29856
  countNonAttachmentPart(part) {
29742
29857
  let overheadDelta = 0;
29743
29858
  let extraMessageDelta = 0;
29744
- if (part.type === "text") return {
29745
- tokens: this.readOrPersistPartEstimate(part, "text", part.text),
29746
- overheadDelta,
29747
- extraMessageDelta
29748
- };
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
+ }
29749
29867
  if (part.type === "tool-invocation") {
29750
29868
  const invocation = part.toolInvocation;
29751
29869
  const state = invocation.state;
@@ -29764,7 +29882,7 @@ var TokenCounter = class TokenCounter {
29764
29882
  tokens += signature.tokens;
29765
29883
  overheadDelta += signature.overheadDelta;
29766
29884
  const reason = invocation.approval?.reason;
29767
- if (reason) tokens += this.readOrPersistPartEstimate(part, "tool-approval-reason", reason);
29885
+ if (reason) tokens += this.readOrPersistMemoizedPartEstimate(part, "tool-approval-reason", [reason], () => reason);
29768
29886
  return {
29769
29887
  tokens,
29770
29888
  overheadDelta,
@@ -29780,15 +29898,12 @@ var TokenCounter = class TokenCounter {
29780
29898
  if (resultForCounting !== void 0 && (typeof resultForCounting !== "string" || resultForCounting.trim().length > 0)) {
29781
29899
  const contentTokens = this.countMultimodalToolResultContent(part, resultForCounting);
29782
29900
  if (contentTokens !== void 0) tokens += contentTokens;
29783
- else {
29784
- const formattedResult = serializeToolResultForTokenCounting(resultForCounting);
29785
- tokens += this.readOrPersistPartEstimate(part, usingStoredModelOutput ? "tool-result-model-output-json" : "tool-result-json", formattedResult);
29786
- }
29901
+ else tokens += this.readOrPersistMemoizedPartEstimate(part, usingStoredModelOutput ? "tool-result-model-output-json" : "tool-result-json", [resultForCounting], () => serializeToolResultForTokenCounting(resultForCounting));
29787
29902
  if (typeof resultForCounting !== "string") overheadDelta -= 12;
29788
29903
  } else {
29789
29904
  const errorText = toolErrorTextToString(invocation.errorText);
29790
29905
  const fallback = invocation.isError ? errorText.trim() ? errorText : "Tool execution failed" : "[empty result]";
29791
- 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);
29792
29907
  }
29793
29908
  return {
29794
29909
  tokens,
@@ -29802,7 +29917,7 @@ var TokenCounter = class TokenCounter {
29802
29917
  tokens += signature.tokens;
29803
29918
  overheadDelta += signature.overheadDelta;
29804
29919
  const reason = invocation.approval?.reason?.trim() ? invocation.approval.reason : "Tool call was not approved by the user";
29805
- tokens += this.readOrPersistPartEstimate(part, "tool-result-denied", reason);
29920
+ tokens += this.readOrPersistMemoizedPartEstimate(part, "tool-result-denied", [reason], () => reason);
29806
29921
  return {
29807
29922
  tokens,
29808
29923
  overheadDelta,
@@ -29816,7 +29931,7 @@ var TokenCounter = class TokenCounter {
29816
29931
  overheadDelta += signature.overheadDelta;
29817
29932
  const errorText = toolErrorTextToString(invocation.errorText);
29818
29933
  const errorMessage = errorText.trim() ? errorText : "Tool execution failed";
29819
- tokens += this.readOrPersistPartEstimate(part, "tool-result-error", errorMessage);
29934
+ tokens += this.readOrPersistMemoizedPartEstimate(part, "tool-result-error", [errorMessage], () => errorMessage);
29820
29935
  return {
29821
29936
  tokens,
29822
29937
  overheadDelta,
@@ -29829,6 +29944,11 @@ var TokenCounter = class TokenCounter {
29829
29944
  overheadDelta,
29830
29945
  extraMessageDelta
29831
29946
  };
29947
+ if (part.type === "step-start") return {
29948
+ tokens: 0,
29949
+ overheadDelta,
29950
+ extraMessageDelta
29951
+ };
29832
29952
  if (part.type === "reasoning") return {
29833
29953
  tokens: 0,
29834
29954
  overheadDelta,
@@ -30119,8 +30239,8 @@ const updateWorkingMemoryTool = (memoryConfig) => {
30119
30239
  }
30120
30240
  const usesMergeSemantics = Boolean(schema);
30121
30241
  const useStateSignals = memoryConfig?.workingMemory?.useStateSignals === true;
30122
- const stateSignalsPreamble = `The current working memory state is delivered to you each turn by the system inside a <working-memory>...</working-memory> block. That block is system-emitted state, NOT something the user typed — never describe it as the user sharing it. Read from it directly when answering. Only call this tool when the user provides genuinely NEW or CHANGED facts that should be persisted; do NOT call it to re-save unchanged data.`;
30123
- const description = schema ? useStateSignals ? `${stateSignalsPreamble} Data is merged with existing memory — only include fields you want to add or update.` : `Update the working memory with new information. Data is merged with existing memory - only include fields you want to add or update. To preserve existing data, omit the field entirely. Arrays are replaced entirely when provided, so pass the complete array or omit it to keep the existing values.` : useStateSignals ? `${stateSignalsPreamble} Pass the full updated Markdown blob as a string in the memory field.` : `Update the working memory with new information. Any data not included will be overwritten. Always pass data as string to the memory field. Never pass an object.`;
30242
+ const stateSignalsPreamble = `The current working memory state is delivered to you each turn by the system inside a <working-memory>...</working-memory> block. That block is system-emitted state, NOT something the user typed \u2014 never describe it as the user sharing it. Read from it directly when answering. Only call this tool when the user provides genuinely NEW or CHANGED facts that should be persisted; do NOT call it to re-save unchanged data.`;
30243
+ const description = schema ? useStateSignals ? `${stateSignalsPreamble} Data is merged with existing memory \u2014 only include fields you want to add or update.` : `Update the working memory with new information. Data is merged with existing memory - only include fields you want to add or update. To preserve existing data, omit the field entirely. Arrays are replaced entirely when provided, so pass the complete array or omit it to keep the existing values.` : useStateSignals ? `${stateSignalsPreamble} Pass the full updated Markdown blob as a string in the memory field.` : `Update the working memory with new information. Any data not included will be overwritten. Always pass data as string to the memory field. Never pass an object.`;
30124
30244
  return (0, _mastra_core_tools.createTool)({
30125
30245
  id: "update-working-memory",
30126
30246
  description,
@@ -31151,8 +31271,8 @@ async function pageGroups({ om, threadId, resourceId, groupId, recordId, directi
31151
31271
  })).count > 0;
31152
31272
  const hasLater = direction === "before" || hasMore;
31153
31273
  const newer = hasLater ? null : await newerMessagesNote(page.at(-1).group, countNewerMessages, pagingThreadId);
31154
- text.unshift(hasEarlier ? `— Browse earlier: ${pagingCall(page[0].group.id, "before", pagingThreadId, page[0].record.id)} —` : "— Start of retained observation history for this thread. —");
31155
- text.push(hasLater ? `— Browse later: ${pagingCall(page.at(-1).group.id, "after", pagingThreadId, page.at(-1).record.id)} —` : newer ? `— End of observation history for this thread. ${newer} —` : "— End of retained observation history for this thread. —");
31274
+ text.unshift(hasEarlier ? `\u2014 Browse earlier: ${pagingCall(page[0].group.id, "before", pagingThreadId, page[0].record.id)} \u2014` : "\u2014 Start of retained observation history for this thread. \u2014");
31275
+ text.push(hasLater ? `\u2014 Browse later: ${pagingCall(page.at(-1).group.id, "after", pagingThreadId, page.at(-1).record.id)} \u2014` : newer ? `\u2014 End of observation history for this thread. ${newer} \u2014` : "\u2014 End of retained observation history for this thread. \u2014");
31156
31276
  text.unshift(`### Observation page\nThread: ${threadTitle || "(untitled)"}\nShowing ${page.length} groups ${requestedDirection === void 0 ? "starting at" : `strictly ${direction}`} \`${groupId}\` (oldest first).`);
31157
31277
  return {
31158
31278
  results: text.join("\n\n"),
@@ -31340,7 +31460,7 @@ async function listThreadsForResource({ memory, resourceId, currentThreadId, pag
31340
31460
  const title = thread.title || "(untitled)";
31341
31461
  const updated = formatTimestamp(thread.updatedAt);
31342
31462
  const created = formatTimestamp(thread.createdAt);
31343
- const marker = isCurrent ? " ← current" : "";
31463
+ const marker = isCurrent ? " \u2190 current" : "";
31344
31464
  lines.push(`- **${title}**${marker}`);
31345
31465
  lines.push(` id: ${thread.id}`);
31346
31466
  lines.push(` updated: ${updated} | created: ${created}`);
@@ -31519,7 +31639,7 @@ async function searchMessagesForResource({ memory, om, resourceId, currentThread
31519
31639
  const groupLine = match.groupId ? `- observation group: ${groupCursor(match.groupId, match.recordId)}` : void 0;
31520
31640
  const scoreLine = `- score: ${match.score.toFixed(2)}`;
31521
31641
  const prev = i > 0 ? ordered[i - 1].match : void 0;
31522
- if (om && prev?.groupId && match.groupId && prev.threadId === match.threadId) sections.push(`— Observation groups may be hidden between these results; continue with ${pagingCall(prev.groupId, "after", includeThreadId ? prev.threadId : void 0, prev.recordId)} —`);
31642
+ if (om && prev?.groupId && match.groupId && prev.threadId === match.threadId) sections.push(`\u2014 Observation groups may be hidden between these results; continue with ${pagingCall(prev.groupId, "after", includeThreadId ? prev.threadId : void 0, prev.recordId)} \u2014`);
31523
31643
  if (suppression) {
31524
31644
  sections.push(`${groupLine}\n thread: ${match.threadId}; ${suppression}`);
31525
31645
  continue;
@@ -32074,7 +32194,7 @@ async function recallAttachmentView({ memory, threadId, resourceId, cursor, part
32074
32194
  const partType = rawPart?.type;
32075
32195
  if (!rawPart || partType !== "image" && partType !== "file") return { messages: `Part ${partIndex} of message ${cursor} is ${rawPart ? `a ${partType ?? "unknown"}-type part` : "missing"}, not an attachment. Call recall with the same cursor and partIndex without viewAttachment to read it.` };
32076
32196
  const resolvedAttachment = resolveViewableAttachment(rawPart);
32077
- if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)} — ${resolvedAttachment.note}` };
32197
+ if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)} \u2014 ${resolvedAttachment.note}` };
32078
32198
  return { content: [{
32079
32199
  type: "text",
32080
32200
  text: formatAttachmentPart(partType, rawPart)
@@ -32477,7 +32597,7 @@ const recallTool = (_memoryConfig, options) => {
32477
32597
  if (!thread) return { error: "Could not resolve current thread." };
32478
32598
  if (isResourceScope && resourceId && thread.resourceId !== resourceId) throw new Error("Thread does not belong to the active resource");
32479
32599
  return {
32480
- threads: `- **${thread.title || "(untitled)"}** ← current\n id: ${thread.id}\n updated: ${formatTimestamp(thread.updatedAt)} | created: ${formatTimestamp(thread.createdAt)}`,
32600
+ threads: `- **${thread.title || "(untitled)"}** \u2190 current\n id: ${thread.id}\n updated: ${formatTimestamp(thread.updatedAt)} | created: ${formatTimestamp(thread.createdAt)}`,
32481
32601
  count: 1,
32482
32602
  page: 0,
32483
32603
  hasMore: false
@@ -33237,9 +33357,10 @@ const suggestedResponseInstructions = `Hint for the agent's immediate next messa
33237
33357
  - "The assistant should wait for the user to respond before continuing."
33238
33358
  - Call the view tool on src/example.ts to continue debugging.`;
33239
33359
  const threadTitleInstructions = `A short, noun-phrase title for this conversation (2-5 words). Examples:
33240
- - "Auth bug fix" — not "Fixing the auth bug"
33241
- - "Dark mode toggle" — not "User wants dark mode toggle added"
33242
- - "Deployment pipeline setup" — not "Setting up deployment pipeline for project"
33360
+ - "Auth bug fix" \u2014 not "Fixing the auth bug"
33361
+ - "Dark mode toggle" \u2014 not "User wants dark mode toggle added"
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.
33243
33364
  Only update when the topic meaningfully changes.`;
33244
33365
  function createCurrentTaskExtractor() {
33245
33366
  return new Extractor({
@@ -34316,7 +34437,7 @@ var SyncObservationStrategy = class extends ObservationStrategy {
34316
34437
  failures: result.extractionFailures,
34317
34438
  previousValues: this.priorExtractedValues,
34318
34439
  rawObservations: result.observations,
34319
- recentMessages: formatMessagesForObserver(this.opts.messages, {
34440
+ recentMessages: () => formatMessagesForObserver(this.opts.messages, {
34320
34441
  maxPartLength: 500,
34321
34442
  timeZone: this.opts.record.observedTimezone
34322
34443
  }),
@@ -34541,7 +34662,7 @@ var AsyncBufferObservationStrategy = class extends ObservationStrategy {
34541
34662
  failures: result.extractionFailures,
34542
34663
  previousValues: this.priorExtractedValues,
34543
34664
  rawObservations: result.observations,
34544
- recentMessages: formatMessagesForObserver(messages, {
34665
+ recentMessages: () => formatMessagesForObserver(messages, {
34545
34666
  maxPartLength: 500,
34546
34667
  timeZone: this.opts.record.observedTimezone
34547
34668
  }),
@@ -34971,7 +35092,7 @@ var ResourceScopedObservationStrategy = class extends ObservationStrategy {
34971
35092
  failures: result.extractionFailures,
34972
35093
  previousValues,
34973
35094
  rawObservations: result.observations,
34974
- recentMessages: formatMessagesForObserver(threadMessages, {
35095
+ recentMessages: () => formatMessagesForObserver(threadMessages, {
34975
35096
  maxPartLength: 500,
34976
35097
  timeZone: this.opts.record.observedTimezone
34977
35098
  }),
@@ -35201,6 +35322,47 @@ ObservationStrategy.create = ((om, opts) => {
35201
35322
  if (deps.scope === "resource" && opts.resourceId) return new ResourceScopedObservationStrategy(deps, opts);
35202
35323
  return new SyncObservationStrategy(deps, opts);
35203
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
+ }
35204
35366
  // src/processors/observational-memory/observation-turn/load-memory-context.ts
35205
35367
  async function loadMemoryContextMessages({ memory, messageList, threadId, resourceId, runState }) {
35206
35368
  const ctx = await memory.getContext({
@@ -35208,7 +35370,8 @@ async function loadMemoryContextMessages({ memory, messageList, threadId, resour
35208
35370
  resourceId,
35209
35371
  runState
35210
35372
  });
35211
- 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");
35212
35375
  return ctx;
35213
35376
  }
35214
35377
  // src/processors/observational-memory/observation-turn/safe-buffer-prefix.ts
@@ -35304,7 +35467,7 @@ var ObservationStep = class {
35304
35467
  }
35305
35468
  /** Step context from prepare(). Throws if prepare() hasn't been called. */
35306
35469
  get context() {
35307
- if (!this._context) throw new Error("Step not prepared yet — call prepare() first");
35470
+ if (!this._context) throw new Error("Step not prepared yet \u2014 call prepare() first");
35308
35471
  return this._context;
35309
35472
  }
35310
35473
  /**
@@ -35415,7 +35578,7 @@ var ObservationStep = class {
35415
35578
  const inputIds = new Set(messageList.get.input.db().map((msg) => msg.id));
35416
35579
  const sealedOutput = safeCandidates.filter((msg) => !inputIds.has(msg.id));
35417
35580
  messageList.removeByIds(sealedOutput.map((msg) => msg.id));
35418
- for (const msg of sealedOutput) messageList.add(msg, "memory");
35581
+ if (sealedOutput.length) messageList.add(sealedOutput, "memory");
35419
35582
  }
35420
35583
  if (!deferred) {
35421
35584
  om.trackBackgroundWork(om.buffer({
@@ -35464,7 +35627,7 @@ var ObservationStep = class {
35464
35627
  }).map((msg) => msg.id);
35465
35628
  inFlightIds = [...new Set(unreadIds)];
35466
35629
  if (messagesToSave.length > 0) {
35467
- for (const msg of messagesToSave) messageList.add(msg, "memory");
35630
+ messageList.add(messagesToSave, "memory");
35468
35631
  try {
35469
35632
  await om.persistMessages(messagesToSave, threadId, resourceId);
35470
35633
  } catch (error) {
@@ -35724,7 +35887,7 @@ var ObservationStep = class {
35724
35887
  const messagesToSeal = messageToSeal ? [messageToSeal] : [];
35725
35888
  this.turn.abortSignal?.throwIfAborted();
35726
35889
  om.sealMessagesForBuffering(messagesToSeal);
35727
- if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation — step-0 seeded response message holds the active id");
35890
+ if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation \u2014 step-0 seeded response message holds the active id");
35728
35891
  else try {
35729
35892
  await this.turn.hooks?.onSyncObservationComplete?.();
35730
35893
  } catch (error) {
@@ -35875,12 +36038,12 @@ var ObservationTurn = class {
35875
36038
  messageList;
35876
36039
  /** The current cached record. Refreshed after mutations (activate/observe/reflect). */
35877
36040
  get record() {
35878
- if (!this._record) throw new Error("Turn not started — call start() first");
36041
+ if (!this._record) throw new Error("Turn not started \u2014 call start() first");
35879
36042
  return this._record;
35880
36043
  }
35881
36044
  /** The context loaded during start(). */
35882
36045
  get context() {
35883
- if (!this._context) throw new Error("Turn not started — call start() first");
36046
+ if (!this._context) throw new Error("Turn not started \u2014 call start() first");
35884
36047
  return this._context;
35885
36048
  }
35886
36049
  /** Whether the turn has been ended and can no longer accept steps. */
@@ -35949,7 +36112,7 @@ var ObservationTurn = class {
35949
36112
  * (its output messages will be saved at the start of the new step's prepare()).
35950
36113
  */
35951
36114
  step(stepNumber) {
35952
- if (!this._started) throw new Error("Turn not started — call start() first");
36115
+ if (!this._started) throw new Error("Turn not started \u2014 call start() first");
35953
36116
  if (this._ended) throw new Error("Turn already ended");
35954
36117
  this._currentStep = new ObservationStep(this, stepNumber);
35955
36118
  return this._currentStep;
@@ -35967,8 +36130,8 @@ var ObservationTurn = class {
35967
36130
  this._ended = true;
35968
36131
  const unsavedInput = messageList.get.input.db();
35969
36132
  const unsavedOutput = messageList.get.response.db();
35970
- const unsavedMessages = [...unsavedInput, ...unsavedOutput];
35971
- 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]));
35972
36135
  const asyncObservationEnabled = this.om.buffering.isAsyncObservationEnabled();
35973
36136
  const bufferOnIdle = this.om.getObservationConfig().bufferOnIdle;
35974
36137
  if (!this.abortSignal?.aborted && asyncObservationEnabled && bufferOnIdle) {
@@ -36172,8 +36335,8 @@ When consolidating observations:
36172
36335
  - Keep what the user explicitly said they have never done, do not know, or refused, and keep every stated preference, rule, and instruction with its meaning intact
36173
36336
  - Prefer many short factual lines over prose summaries. Do not replace facts with generalities like "discussed travel plans"
36174
36337
  - Combine related items where it makes sense (e.g., "agent called view tool 5 times on file x")
36175
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36176
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
36338
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36339
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
36177
36340
  - Condense the wording of older observations more than recent ones, but keep their facts
36178
36341
 
36179
36342
  CRITICAL: USER ASSERTIONS vs QUESTIONS
@@ -36195,23 +36358,23 @@ When observations contain <thread id="..."> sections:
36195
36358
  Example input:
36196
36359
  <thread id="thread-1">
36197
36360
  Date: Dec 4, 2025
36198
- * 🔴 (14:30) User prefers TypeScript
36199
- * 🟡 (14:35) Working on auth feature
36361
+ * \u{1F534} (14:30) User prefers TypeScript
36362
+ * \u{1F7E1} (14:35) Working on auth feature
36200
36363
  </thread>
36201
36364
  <thread id="thread-2">
36202
36365
  Date: Dec 4, 2025
36203
- * 🔴 (15:00) User prefers TypeScript
36204
- * 🟡 (15:05) Debugging API endpoint
36366
+ * \u{1F534} (15:00) User prefers TypeScript
36367
+ * \u{1F7E1} (15:05) Debugging API endpoint
36205
36368
  </thread>
36206
36369
 
36207
36370
  Example output (consolidated):
36208
36371
  Date: Dec 4, 2025
36209
- * 🔴 (14:30) User prefers TypeScript
36372
+ * \u{1F534} (14:30) User prefers TypeScript
36210
36373
  <thread id="thread-1">
36211
- * 🟡 (14:35) Working on auth feature
36374
+ * \u{1F7E1} (14:35) Working on auth feature
36212
36375
  </thread>
36213
36376
  <thread id="thread-2">
36214
- * 🟡 (15:05) Debugging API endpoint
36377
+ * \u{1F7E1} (15:05) Debugging API endpoint
36215
36378
  </thread>
36216
36379
 
36217
36380
  === OUTPUT FORMAT ===
@@ -36242,8 +36405,8 @@ Please re-process with slightly more compression:
36242
36405
  - Memory is getting long - use a more condensed style throughout
36243
36406
  - Combine related items more aggressively but do not lose important specific details of names, places, events, and people
36244
36407
  - Combine repeated similar tool calls (e.g. multiple file views, searches, or edits in the same area) into a single summary line describing what was explored/changed and the outcome
36245
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36246
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
36408
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36409
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
36247
36410
 
36248
36411
  Aim for a 8/10 detail level.
36249
36412
  `,
@@ -36259,8 +36422,8 @@ Please re-process with much more aggressive compression:
36259
36422
  - Combine related items aggressively but do not lose important specific details of names, places, events, and people
36260
36423
  - Combine repeated similar tool calls (e.g. multiple file views, searches, or edits in the same area) into a single summary line describing what was explored/changed and the outcome
36261
36424
  - If the same file or module is mentioned across many observations, merge into one entry covering the full arc
36262
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36263
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
36425
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36426
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
36264
36427
  - Remove redundant information and merge overlapping observations
36265
36428
 
36266
36429
  Aim for a 6/10 detail level.
@@ -36271,14 +36434,14 @@ Aim for a 6/10 detail level.
36271
36434
  Your previous reflections have failed to compress sufficiently after multiple attempts.
36272
36435
 
36273
36436
  Please re-process with maximum compression:
36274
- - Summarize the oldest observations (first 50-70%) into brief high-level paragraphs — only key facts, decisions, and outcomes
36437
+ - Summarize the oldest observations (first 50-70%) into brief high-level paragraphs \u2014 only key facts, decisions, and outcomes
36275
36438
  - For the most recent observations (last 30-50%), retain important details but still use a condensed style
36276
- - Ruthlessly merge related observations — if 10 observations are about the same topic, combine into 1-2 lines
36277
- - Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries — drop individual steps entirely
36278
- - Drop procedural details (tool calls, retries, intermediate steps) — keep only final outcomes
36439
+ - Ruthlessly merge related observations \u2014 if 10 observations are about the same topic, combine into 1-2 lines
36440
+ - Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries \u2014 drop individual steps entirely
36441
+ - Drop procedural details (tool calls, retries, intermediate steps) \u2014 keep only final outcomes
36279
36442
  - Drop observations that are no longer relevant or have been superseded by newer information
36280
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36281
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
36443
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36444
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
36282
36445
  - Preserve: names, dates, decisions, errors, user preferences, and architectural choices
36283
36446
 
36284
36447
  Aim for a 4/10 detail level.
@@ -36289,14 +36452,14 @@ Aim for a 4/10 detail level.
36289
36452
  Multiple compression attempts have failed. The content may already be dense from a prior reflection.
36290
36453
 
36291
36454
  You MUST dramatically reduce the number of observations while keeping the standard observation format (date groups with bullet points and priority emojis):
36292
- - Tool call observations are the biggest source of bloat. Collapse ALL tool call sequences into outcome-only observations — e.g. 10 observations about viewing/searching/editing files become 1 observation about what was actually learned or achieved (e.g. "Investigated auth module and found token validation was skipping expiry check")
36293
- - Never preserve individual tool calls (viewed file X, searched for Y, ran build) — only preserve what was discovered or accomplished
36455
+ - Tool call observations are the biggest source of bloat. Collapse ALL tool call sequences into outcome-only observations \u2014 e.g. 10 observations about viewing/searching/editing files become 1 observation about what was actually learned or achieved (e.g. "Investigated auth module and found token validation was skipping expiry check")
36456
+ - Never preserve individual tool calls (viewed file X, searched for Y, ran build) \u2014 only preserve what was discovered or accomplished
36294
36457
  - Consolidate many related observations into single, more generic observations
36295
36458
  - Merge all same-day date groups into at most 2-3 date groups per day
36296
36459
  - For older content, each topic or task should be at most 1-2 observations capturing the key outcome
36297
36460
  - For recent content, retain more detail but still merge related items aggressively
36298
36461
  - If multiple observations describe incremental progress on the same task, keep only the final state
36299
- - Preserve ✅ completion markers and their outcomes but merge related completions into fewer lines
36462
+ - Preserve \u2705 completion markers and their outcomes but merge related completions into fewer lines
36300
36463
  - Preserve: user preferences, key decisions, architectural choices, and unresolved issues
36301
36464
 
36302
36465
  Aim for a 2/10 detail level. Fewer, more generic observations are better than many specific ones that exceed the budget.
@@ -36720,7 +36883,7 @@ var ReflectorRunner = class {
36720
36883
  operationType: "reflection",
36721
36884
  startedAt: streamContext.startedAt,
36722
36885
  tokensAttempted: originalTokens,
36723
- error: `Did not compress below threshold (${originalTokens} → ${reflectedTokens}, target: ${targetThreshold}), retrying at level ${currentLevel + 1}`,
36886
+ error: `Did not compress below threshold (${originalTokens} \u2192 ${reflectedTokens}, target: ${targetThreshold}), retrying at level ${currentLevel + 1}`,
36724
36887
  retrying: true,
36725
36888
  recordId: streamContext.recordId,
36726
36889
  threadId: streamContext.threadId
@@ -36750,7 +36913,7 @@ var ReflectorRunner = class {
36750
36913
  }
36751
36914
  currentLevel = Math.min(currentLevel + 1, maxLevel);
36752
36915
  }
36753
- if (observations.trim().length > 0 && parsed.observations.trim().length === 0) throw new Error(`Reflector produced empty output after ${attemptNumber} attempt(s)${parsed.degenerate ? " (degenerate repetition)" : ""} — refusing to commit an empty reflection over ${originalTokens} observation tokens`);
36916
+ if (observations.trim().length > 0 && parsed.observations.trim().length === 0) throw new Error(`Reflector produced empty output after ${attemptNumber} attempt(s)${parsed.degenerate ? " (degenerate repetition)" : ""} \u2014 refusing to commit an empty reflection over ${originalTokens} observation tokens`);
36754
36917
  const structuredExtraction = await extractStructuredValues({
36755
36918
  agent,
36756
36919
  source: "reflector",
@@ -36891,7 +37054,7 @@ var ReflectorRunner = class {
36891
37054
  const reflectedObservationLineCount = linesToReflect;
36892
37055
  const sliceTokenEstimate = Math.round(avgTokensPerLine * linesToReflect);
36893
37056
  const compressionTarget = Math.round(sliceTokenEstimate * .75);
36894
- omDebug(`[OM:reflect] doAsyncBufferedReflection: slicing observations for reflection — totalLines=${totalLines}, avgTokPerLine=${avgTokensPerLine.toFixed(1)}, activationPointTokens=${activationPointTokens}, linesToReflect=${linesToReflect}/${totalLines}, sliceTokenEstimate=${sliceTokenEstimate}, compressionTarget=${compressionTarget}`);
37057
+ omDebug(`[OM:reflect] doAsyncBufferedReflection: slicing observations for reflection \u2014 totalLines=${totalLines}, avgTokPerLine=${avgTokensPerLine.toFixed(1)}, activationPointTokens=${activationPointTokens}, linesToReflect=${linesToReflect}/${totalLines}, sliceTokenEstimate=${sliceTokenEstimate}, compressionTarget=${compressionTarget}`);
36895
37058
  omDebug(`[OM:reflect] doAsyncBufferedReflection: starting reflector call, recordId=${currentRecord.id}, observationTokens=${sliceTokenEstimate}, compressionTarget=${compressionTarget} (inputTokens), activeObsLength=${activeObservations.length}, reflectedLineCount=${reflectedObservationLineCount}`);
36896
37059
  if (writer) {
36897
37060
  const startMarker = createBufferingStartMarker({
@@ -37063,7 +37226,7 @@ var ReflectorRunner = class {
37063
37226
  const unreflectedTailTokens = unreflectedContent ? this.tokenCounter.countObservations(unreflectedContent) : 0;
37064
37227
  const bufferedReflectionTokens = freshRecord.bufferedReflectionTokens ?? 0;
37065
37228
  if (unreflectedTailTokens < bufferedReflectionTokens) {
37066
- omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation — unreflectedTailTokens=${unreflectedTailTokens} < bufferedReflectionTokens=${bufferedReflectionTokens}; keeping buffer for threshold activation`);
37229
+ omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation \u2014 unreflectedTailTokens=${unreflectedTailTokens} < bufferedReflectionTokens=${bufferedReflectionTokens}; keeping buffer for threshold activation`);
37067
37230
  return {
37068
37231
  status: "suppressed",
37069
37232
  reason: "composition"
@@ -37074,7 +37237,7 @@ var ReflectorRunner = class {
37074
37237
  const regularActivationTarget = reflectThreshold * (1 - bufferActivation);
37075
37238
  const minCombinedTokens = Math.round(regularActivationTarget * EARLY_ACTIVATION_SIZE_FLOOR_RATIO);
37076
37239
  if (combinedTokenCount < minCombinedTokens) {
37077
- omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation — combinedTokenCount=${combinedTokenCount} < minCombinedTokens=${minCombinedTokens} (${EARLY_ACTIVATION_SIZE_FLOOR_RATIO * 100}% of regular activation target ${Math.round(regularActivationTarget)}, threshold=${reflectThreshold}, bufferActivation=${bufferActivation}); keeping buffer for threshold activation`);
37240
+ omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation \u2014 combinedTokenCount=${combinedTokenCount} < minCombinedTokens=${minCombinedTokens} (${EARLY_ACTIVATION_SIZE_FLOOR_RATIO * 100}% of regular activation target ${Math.round(regularActivationTarget)}, threshold=${reflectThreshold}, bufferActivation=${bufferActivation}); keeping buffer for threshold activation`);
37078
37241
  return {
37079
37242
  status: "suppressed",
37080
37243
  reason: "size"
@@ -37203,7 +37366,7 @@ var ReflectorRunner = class {
37203
37366
  omDebug(`[OM:reflect] isReflecting=true and active in this process, skipping`);
37204
37367
  return;
37205
37368
  }
37206
- omDebug(`[OM:reflect] isReflecting=true but NOT active in this process — stale flag from dead process, clearing`);
37369
+ omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
37207
37370
  await this.storage.setReflectingFlag(record.id, false);
37208
37371
  }
37209
37372
  if (this.buffering.isAsyncReflectionEnabled()) {
@@ -37217,15 +37380,15 @@ var ReflectorRunner = class {
37217
37380
  else {
37218
37381
  const activationPoint = reflectThreshold * this.reflectionConfig.bufferActivation;
37219
37382
  if (observationTokens < activationPoint) {
37220
- omDebug(`[OM:reflect] skipping async reflection — observationTokens (${observationTokens}) below activation point (${activationPoint}), triggered by ${activationTriggeredBy}`);
37383
+ omDebug(`[OM:reflect] skipping async reflection \u2014 observationTokens (${observationTokens}) below activation point (${activationPoint}), triggered by ${activationTriggeredBy}`);
37221
37384
  return;
37222
37385
  }
37223
37386
  const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
37224
37387
  if (this.buffering.isAsyncBufferingInProgress(bufferKey) || BufferingCoordinator.lastBufferedBoundary.has(bufferKey)) {
37225
- omDebug(`[OM:reflect] skipping async reflection — reflection buffer already active or present for ${bufferKey}`);
37388
+ omDebug(`[OM:reflect] skipping async reflection \u2014 reflection buffer already active or present for ${bufferKey}`);
37226
37389
  return;
37227
37390
  }
37228
- omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) — starting background reflection`);
37391
+ omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) \u2014 starting background reflection`);
37229
37392
  this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
37230
37393
  return;
37231
37394
  }
@@ -37233,7 +37396,7 @@ var ReflectorRunner = class {
37233
37396
  if (activationTriggeredBy === "threshold") {
37234
37397
  const suppressedAtTokens = this.syncReflectionSuppression.get(lockKey);
37235
37398
  if (suppressedAtTokens !== void 0 && observationTokens === suppressedAtTokens) {
37236
- omDebug(`[OM:reflect] skipping sync reflection — observations unchanged at ${observationTokens} tokens since the last unproductive attempt; retrying once they change`);
37399
+ omDebug(`[OM:reflect] skipping sync reflection \u2014 observations unchanged at ${observationTokens} tokens since the last unproductive attempt; retrying once they change`);
37237
37400
  return;
37238
37401
  }
37239
37402
  }
@@ -38076,7 +38239,7 @@ var ObservationalMemory = class ObservationalMemory {
38076
38239
  const asyncBufferingDisabled = config.observation?.bufferTokens === false || config.scope === "resource" && !userExplicitlyConfiguredAsync;
38077
38240
  if (isSharedBudget && !asyncBufferingDisabled) {
38078
38241
  if (userExplicitlyConfiguredAsync) throw new Error("shareTokenBudget requires async buffering to be disabled (this is a temporary limitation). Add observation: { bufferTokens: false } to your config:\n\n observationalMemory: {\n shareTokenBudget: true,\n observation: { bufferTokens: false },\n }\n\nRemove any other async buffering settings (bufferTokens, bufferActivation, blockAfter).");
38079
- else throw new Error("shareTokenBudget requires async buffering to be disabled (this is a temporary limitation). Add observation: { bufferTokens: false } to your config:\n\n observationalMemory: {\n shareTokenBudget: true,\n observation: { bufferTokens: false },\n }\n\nAsync buffering is enabled by default — this opt-out is only needed when using shareTokenBudget.");
38242
+ else throw new Error("shareTokenBudget requires async buffering to be disabled (this is a temporary limitation). Add observation: { bufferTokens: false } to your config:\n\n observationalMemory: {\n shareTokenBudget: true,\n observation: { bufferTokens: false },\n }\n\nAsync buffering is enabled by default \u2014 this opt-out is only needed when using shareTokenBudget.");
38080
38243
  }
38081
38244
  const observationActivateAfterIdle = config.observation?.activateAfterIdle ?? config.activateAfterIdle;
38082
38245
  const observationActivateAfterIdlePath = config.observation?.activateAfterIdle !== void 0 ? "observation.activateAfterIdle" : "activateAfterIdle";
@@ -38173,7 +38336,7 @@ var ObservationalMemory = class ObservationalMemory {
38173
38336
  hasWarnedResourceScopeDeprecation = true;
38174
38337
  console.warn("[Mastra] Observational memory `scope: 'resource'` is deprecated and will be removed in a future release because it works much worse than thread scope for prompt caching and agent understanding. Remove `scope` to use the default thread scope, and enable `retrieval` for cross-thread recall. See https://mastra.ai/docs/memory/observational-memory#resource-scope-deprecated");
38175
38338
  }
38176
- omDebug(`[OM:init] new ObservationalMemory instance created — scope=${this.scope}, messageTokens=${JSON.stringify(this.observationConfig.messageTokens)}, obsAsyncEnabled=${this.buffering.isAsyncObservationEnabled()}, bufferTokens=${this.observationConfig.bufferTokens}, bufferActivation=${this.observationConfig.bufferActivation}, blockAfter=${this.observationConfig.blockAfter}, reflectionTokens=${this.reflectionConfig.observationTokens}, refAsyncEnabled=${this.buffering.isAsyncReflectionEnabled()}, refAsyncActivation=${this.reflectionConfig.bufferActivation}, refBlockAfter=${this.reflectionConfig.blockAfter}`);
38339
+ omDebug(`[OM:init] new ObservationalMemory instance created \u2014 scope=${this.scope}, messageTokens=${JSON.stringify(this.observationConfig.messageTokens)}, obsAsyncEnabled=${this.buffering.isAsyncObservationEnabled()}, bufferTokens=${this.observationConfig.bufferTokens}, bufferActivation=${this.observationConfig.bufferActivation}, blockAfter=${this.observationConfig.blockAfter}, reflectionTokens=${this.reflectionConfig.observationTokens}, refAsyncEnabled=${this.buffering.isAsyncReflectionEnabled()}, refAsyncActivation=${this.reflectionConfig.bufferActivation}, refBlockAfter=${this.reflectionConfig.blockAfter}`);
38177
38340
  }
38178
38341
  __registerMastra(mastra) {
38179
38342
  this.mastra = mastra;
@@ -38454,7 +38617,7 @@ var ObservationalMemory = class ObservationalMemory {
38454
38617
  threadId: null,
38455
38618
  resourceId: resourceId ?? threadId
38456
38619
  };
38457
- if (!threadId) throw new Error("ObservationalMemory (scope: 'thread') requires a threadId, but received an empty value. This is a bug — getThreadContext should have caught this earlier.");
38620
+ if (!threadId) throw new Error("ObservationalMemory (scope: 'thread') requires a threadId, but received an empty value. This is a bug \u2014 getThreadContext should have caught this earlier.");
38458
38621
  return {
38459
38622
  threadId,
38460
38623
  resourceId: resourceId ?? threadId
@@ -38765,7 +38928,7 @@ var ObservationalMemory = class ObservationalMemory {
38765
38928
  const isImportant = new Array(totalCount);
38766
38929
  for (let i = 0; i < totalCount; i++) {
38767
38930
  lineTokens[i] = this.tokenCounter.countString(lines[i]);
38768
- isImportant[i] = lines[i].includes("🔴") || lines[i].includes("✅");
38931
+ isImportant[i] = lines[i].includes("\u{1F534}") || lines[i].includes("\u2705");
38769
38932
  }
38770
38933
  const suffixTokens = new Array(totalCount + 1);
38771
38934
  suffixTokens[totalCount] = 0;
@@ -38877,18 +39040,86 @@ var ObservationalMemory = class ObservationalMemory {
38877
39040
  * to detect already-persisted messages, avoiding redundant DB operations.
38878
39041
  *
38879
39042
  * Messages with observation markers are always saved (upserted) even if sealed,
38880
- * 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.
38881
39047
  */
38882
- async persistMessages(messagesToSave, threadId, resourceId) {
39048
+ async persistMessages(messagesToSave, threadId, resourceId, resaveIds) {
38883
39049
  const filteredMessages = [];
38884
- for (const msg of messagesToSave) if (!!(msg.content?.metadata)?.mastra?.sealed) {
38885
- if (findLastCompletedObservationBoundary(msg) !== -1) filteredMessages.push(msg);
38886
- } 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
+ }
38887
39056
  if (filteredMessages.length > 0) await this.messageHistory.persistMessages({
38888
39057
  messages: filteredMessages,
38889
39058
  threadId,
38890
39059
  resourceId
38891
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 });
38892
39123
  }
38893
39124
  /**
38894
39125
  * Load messages from storage that haven't been observed yet.
@@ -39098,7 +39329,7 @@ ${formattedMessages}
39098
39329
  resourceId: freshRecord.resourceId ?? void 0
39099
39330
  });
39100
39331
  } catch (err) {
39101
- omError("[OM] Failed to persist sealed messages before buffering — skipping observation cycle", err);
39332
+ omError("[OM] Failed to persist sealed messages before buffering \u2014 skipping observation cycle", err);
39102
39333
  return;
39103
39334
  }
39104
39335
  const cycleId = `buffer-obs-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
@@ -40248,7 +40479,7 @@ ${formattedMessages}
40248
40479
  usage: void 0
40249
40480
  };
40250
40481
  }
40251
- omDebug(`[OM:reflect] isReflecting=true but NOT active in this process — stale flag from dead process, clearing`);
40482
+ omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
40252
40483
  await this.storage.setReflectingFlag(record.id, false);
40253
40484
  }
40254
40485
  await this.storage.setReflectingFlag(record.id, true);
@@ -40483,7 +40714,7 @@ ${formattedMessages}
40483
40714
  // src/processors/observational-memory/temporal-markers.ts
40484
40715
  const TEMPORAL_GAP_REMINDER_TYPE = "temporal-gap";
40485
40716
  function getTemporalGapReminderText(gapText, timestamp) {
40486
- return `${gapText} — ${formatTemporalTimestamp(new Date(timestamp))}`;
40717
+ return `${gapText} \u2014 ${formatTemporalTimestamp(new Date(timestamp))}`;
40487
40718
  }
40488
40719
  function getTemporalGapReminderMetadata(message, gapText, gapMs, timestamp) {
40489
40720
  const formattedTimestamp = formatTemporalTimestamp(new Date(timestamp));
@@ -40691,11 +40922,12 @@ var ObservationalMemoryProcessor = class {
40691
40922
  state.__omTurn = void 0;
40692
40923
  if (!activeTurn || activeTurn.ended) return;
40693
40924
  const terminalList = messageList ?? activeTurn.messageList;
40694
- 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);
40695
40927
  try {
40696
40928
  await activeTurn.end(terminalList);
40697
40929
  } catch (error) {
40698
- 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(() => {});
40699
40931
  throw error;
40700
40932
  }
40701
40933
  }
@@ -40705,14 +40937,14 @@ var ObservationalMemoryProcessor = class {
40705
40937
  omDebug(`[OM:processInputStep:ENTER] step=${stepNumber}, hasMastraMemory=${!!requestContext?.get("MastraMemory")}, hasMemoryInfo=${!!messageList?.serialize()?.memoryInfo?.threadId}`);
40706
40938
  const context = this.engine.getThreadContext(requestContext, messageList);
40707
40939
  if (!context) {
40708
- omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null — returning early`);
40940
+ omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null \u2014 returning early`);
40709
40941
  return messageList;
40710
40942
  }
40711
40943
  const gatewayMemoryManaged = await isGatewayMemoryManaged(model);
40712
40944
  state[GATEWAY_STATE_KEY] = gatewayMemoryManaged;
40713
40945
  if (gatewayMemoryManaged) {
40714
40946
  await this.endActiveTurn(state);
40715
- omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory — skipping local processing`);
40947
+ omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory \u2014 skipping local processing`);
40716
40948
  return messageList;
40717
40949
  }
40718
40950
  const { threadId, resourceId } = context;
@@ -40837,6 +41069,7 @@ var ObservationalMemoryProcessor = class {
40837
41069
  this.turn.responseMessageId = responseMessageId;
40838
41070
  {
40839
41071
  const step = this.turn.step(stepNumber);
41072
+ const resaveCounted = resaveCountedMessagesFor(messageList, threadId);
40840
41073
  let ctx;
40841
41074
  try {
40842
41075
  ctx = await step.prepare();
@@ -40871,6 +41104,7 @@ var ObservationalMemoryProcessor = class {
40871
41104
  threadId,
40872
41105
  resourceId
40873
41106
  });
41107
+ resaveCounted();
40874
41108
  const finalTotalPending = ctx.status.pendingTokens;
40875
41109
  try {
40876
41110
  await runOMCommit(this.engine.buffering.getLockKey(threadId, resourceId), () => this.engine.getStorage().setPendingMessageTokens(turnRecord.id, finalTotalPending), { abortSignal });
@@ -40910,6 +41144,7 @@ var ObservationalMemoryProcessor = class {
40910
41144
  return this.engine.getTokenCounter().runWithModelContext(state.__omActorModelContext, async () => {
40911
41145
  if ((0, _mastra_core_memory.parseMemoryRequestContext)(requestContext)?.memoryConfig?.readOnly) return messageList;
40912
41146
  const persistenceMessageList = messageList.cloneForPersistence();
41147
+ this.engine.getTokenCounter().countMessages(persistenceMessageList.get.response.db());
40913
41148
  const turn = asLiveTurn(state.__omTurn) ?? this.turn;
40914
41149
  const liveTurn = turn && !turn.ended ? turn : void 0;
40915
41150
  if (liveTurn) await liveTurn.end(persistenceMessageList);
@@ -40917,8 +41152,9 @@ var ObservationalMemoryProcessor = class {
40917
41152
  state.__omTurn = void 0;
40918
41153
  if (!liveTurn) {
40919
41154
  const newOutput = persistenceMessageList.get.response.db();
40920
- const messagesToSave = [...persistenceMessageList.get.input.db(), ...newOutput];
40921
- 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));
40922
41158
  }
40923
41159
  return messageList;
40924
41160
  });
@@ -40933,7 +41169,7 @@ var ObservationalMemoryProcessor = class {
40933
41169
  if (!context) return;
40934
41170
  if ((0, _mastra_core_memory.parseMemoryRequestContext)(requestContext)?.memoryConfig?.readOnly) return;
40935
41171
  state[CONTEXT_OVERFLOW_STEP_KEY] = stepNumber;
40936
- omDebug(`[OM:processAPIError] context overflow at step ${stepNumber} — observing pending messages`);
41172
+ omDebug(`[OM:processAPIError] context overflow at step ${stepNumber} \u2014 observing pending messages`);
40937
41173
  const { threadId, resourceId } = context;
40938
41174
  await this.engine.waitForBuffering(threadId, resourceId, void 0, args.abortSignal);
40939
41175
  const messages = getObservableMessages(messageList);