@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.
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +87 -87
- package/dist/docs/references/docs-harness-background-tasks.md +4 -1
- package/dist/docs/references/docs-knowledge-overview.md +1 -1
- package/dist/docs/references/integrations-databases-libsql.md +1 -1
- package/dist/docs/references/reference-memory-observational-memory.md +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/processors/index.cjs +1 -1
- package/dist/processors/index.js +1 -1
- package/dist/processors/observational-memory/extracted-values.d.ts +5 -1
- package/dist/processors/observational-memory/observational-memory.d.ts +12 -2
- package/dist/processors/observational-memory/resave-counted-messages.d.ts +23 -0
- package/dist/processors/observational-memory/retry.d.ts +11 -1
- package/dist/processors/observational-memory/token-counter.d.ts +20 -3
- package/dist/{src-CDv__4kY.js → src-C6oJP8WI.js} +437 -201
- package/dist/{src-CDIIMmAU.cjs → src-DxOLwFhL.cjs} +437 -201
- package/package.json +5 -5
|
@@ -24261,14 +24261,14 @@ function getRetrievalInstructions(scope = "resource", customInstructions, search
|
|
|
24261
24261
|
The recall tool works across ALL of this user's conversation threads, not just the current one.
|
|
24262
24262
|
|
|
24263
24263
|
- 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.
|
|
24264
|
-
- Use \`mode: "messages"\` for original wording or details behind an observation
|
|
24264
|
+
- 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.
|
|
24265
24265
|
- 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.
|
|
24266
24266
|
|
|
24267
|
-
**If search results look irrelevant, do not give up.** Search only covers content that has been indexed
|
|
24267
|
+
**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
|
|
24268
24268
|
The recall tool works across ALL of this user's conversation threads, not just the current one.
|
|
24269
24269
|
|
|
24270
24270
|
- 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.
|
|
24271
|
-
- Use \`mode: "messages"\` when you know the thread
|
|
24271
|
+
- Use \`mode: "messages"\` when you know the thread \u2014 pass \`threadId\` to read another thread, or a \`cursor\` from an observation-group range.
|
|
24272
24272
|
|
|
24273
24273
|
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
|
|
24274
24274
|
The recall tool is limited to the current conversation thread.
|
|
@@ -24293,7 +24293,7 @@ When searches keep returning the same groups, often as already-in-context refere
|
|
|
24293
24293
|
"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.
|
|
24294
24294
|
|
|
24295
24295
|
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.` : "";
|
|
24296
|
-
const base = `## Recall
|
|
24296
|
+
const base = `## Recall \u2014 looking up source messages
|
|
24297
24297
|
|
|
24298
24298
|
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.
|
|
24299
24299
|
|
|
@@ -24304,13 +24304,13 @@ Groups marked \`kind="reflection"\` (rendered as \`_kind: reflection_\`) are los
|
|
|
24304
24304
|
|
|
24305
24305
|
### When to use recall
|
|
24306
24306
|
- The user asks you to **repeat, show, or reproduce** something from a past conversation
|
|
24307
|
-
- The user asks for **exact content**
|
|
24307
|
+
- The user asks for **exact content** \u2014 code, text, quotes, error messages, URLs, file paths, specific numbers
|
|
24308
24308
|
- 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)
|
|
24309
24309
|
- You want to **verify or expand on** an observation before responding
|
|
24310
24310
|
- 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
|
|
24311
24311
|
- 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
|
|
24312
24312
|
- Relevant details are missing, ambiguous, or conflicting in the current observations${isResource ? `
|
|
24313
|
-
- The user references another conversation that your observations don't cover
|
|
24313
|
+
- 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` : ""}
|
|
24314
24314
|
|
|
24315
24315
|
**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.
|
|
24316
24316
|
|
|
@@ -24345,17 +24345,17 @@ Each range has the format \`startId:endId\` where both are message IDs separated
|
|
|
24345
24345
|
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.
|
|
24346
24346
|
|
|
24347
24347
|
- 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.
|
|
24348
|
-
- Use \`partIndex\` with a cursor to fetch a single part at full detail
|
|
24348
|
+
- 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.
|
|
24349
24349
|
|
|
24350
24350
|
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.
|
|
24351
24351
|
|
|
24352
24352
|
### Following up on truncated parts
|
|
24353
24353
|
Low-detail results may include truncation hints like:
|
|
24354
|
-
\`[truncated
|
|
24354
|
+
\`[truncated \u2014 call recall cursor="..." partIndex=N detail="high" for full content]\`
|
|
24355
24355
|
|
|
24356
24356
|
**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.
|
|
24357
24357
|
|
|
24358
|
-
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
|
|
24358
|
+
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.
|
|
24359
24359
|
|
|
24360
24360
|
### When recall is NOT needed
|
|
24361
24361
|
- The user is asking for a high-level summary and your observations already cover it
|
|
@@ -24752,6 +24752,15 @@ function buildThreadMetadataFromExtractedValues(extractors, values) {
|
|
|
24752
24752
|
async function applyExtractorHooks(opts) {
|
|
24753
24753
|
const values = normalizeExtractedValues(opts.values) ?? {};
|
|
24754
24754
|
const failures = [...opts.failures ?? []];
|
|
24755
|
+
let recentMessages;
|
|
24756
|
+
let recentMessagesResolved = false;
|
|
24757
|
+
const resolveRecentMessages = () => {
|
|
24758
|
+
if (!recentMessagesResolved) {
|
|
24759
|
+
recentMessages = typeof opts.recentMessages === "function" ? opts.recentMessages() : opts.recentMessages;
|
|
24760
|
+
recentMessagesResolved = true;
|
|
24761
|
+
}
|
|
24762
|
+
return recentMessages;
|
|
24763
|
+
};
|
|
24755
24764
|
for (const extractor of opts.extractors) {
|
|
24756
24765
|
const isHook = extractor.mode === "hook";
|
|
24757
24766
|
const hasValue = Object.prototype.hasOwnProperty.call(values, extractor.slug);
|
|
@@ -24771,7 +24780,9 @@ async function applyExtractorHooks(opts) {
|
|
|
24771
24780
|
previous: isHook ? void 0 : opts.previousValues?.[extractor.slug],
|
|
24772
24781
|
current,
|
|
24773
24782
|
rawObservations: opts.rawObservations,
|
|
24774
|
-
recentMessages
|
|
24783
|
+
get recentMessages() {
|
|
24784
|
+
return resolveRecentMessages();
|
|
24785
|
+
},
|
|
24775
24786
|
mainAgent: opts.mainAgent,
|
|
24776
24787
|
memory: opts.memory,
|
|
24777
24788
|
sendSignal: opts.sendSignal,
|
|
@@ -25017,6 +25028,17 @@ function isTransientLLMError(error) {
|
|
|
25017
25028
|
return visit(error);
|
|
25018
25029
|
}
|
|
25019
25030
|
/**
|
|
25031
|
+
* Returns true when the error says the provider account has no credits or quota left, as core's
|
|
25032
|
+
* provider-error classifier decides it. These can carry a retryable status (OpenAI's are HTTP 429,
|
|
25033
|
+
* the status of a rate limit), so `withRetry` stops on them even though `isTransientLLMError`
|
|
25034
|
+
* matches: the account stays unusable until someone adds credits. Rate limits are still retried.
|
|
25035
|
+
*
|
|
25036
|
+
* @internal
|
|
25037
|
+
*/
|
|
25038
|
+
function isExhaustedAccountError(error) {
|
|
25039
|
+
return classifyProviderError(error) === "quota";
|
|
25040
|
+
}
|
|
25041
|
+
/**
|
|
25020
25042
|
* Compute the backoff delay (ms) for the Nth retry (0-indexed).
|
|
25021
25043
|
*
|
|
25022
25044
|
* Exponential growth (`initialDelayMs * backoffFactor^attempt`) capped at
|
|
@@ -25100,7 +25122,8 @@ async function attemptWithIdleTimeout(fn, label, idleTimeoutMs, abortSignal) {
|
|
|
25100
25122
|
/**
|
|
25101
25123
|
* Run `fn` with retries on transient transport-class errors.
|
|
25102
25124
|
*
|
|
25103
|
-
* Non-transient errors (auth, validation, schema, etc.)
|
|
25125
|
+
* Non-transient errors (auth, validation, schema, etc.) and errors from an
|
|
25126
|
+
* account with no credits or quota left (see `isExhaustedAccountError`) are rethrown
|
|
25104
25127
|
* immediately. User-initiated aborts are rethrown without delay.
|
|
25105
25128
|
*
|
|
25106
25129
|
* @internal
|
|
@@ -25116,7 +25139,7 @@ async function withRetry(fn, opts) {
|
|
|
25116
25139
|
} catch (error) {
|
|
25117
25140
|
if (abortSignal?.aborted) throw error;
|
|
25118
25141
|
if (!(error instanceof OmModelCallTimeoutError) && hasAbortInChain(error)) throw error;
|
|
25119
|
-
if (attempt >= maxRetries || !isTransientLLMError(error)) {
|
|
25142
|
+
if (attempt >= maxRetries || !isTransientLLMError(error) || isExhaustedAccountError(error)) {
|
|
25120
25143
|
if (attempt > 0) omDebug(`[OM:retry:${label}] giving up after ${attempt} retry/retries: ${error instanceof Error ? error.message : String(error)}`);
|
|
25121
25144
|
throw error;
|
|
25122
25145
|
}
|
|
@@ -25530,7 +25553,7 @@ const YEAR = String.raw`(?:19|20|21)\d{2}(?!\d)`;
|
|
|
25530
25553
|
const MERIDIEM = String.raw`(?:[AaPp]\.[Mm]\.|[AaPp][Mm]\b)`;
|
|
25531
25554
|
const TIME = String.raw`(?:,?\s+(?:at\s+)?\d{1,2}:\d{2}(?:\s*${MERIDIEM})?|\s+at\s+\d{1,2}\s*${MERIDIEM})`;
|
|
25532
25555
|
const QUALIFIER = String.raw`(?:(?:early|mid|late)[- ](?:to[- ](?:early|mid|late)[- ])?)`;
|
|
25533
|
-
const RANGE_SEP = String.raw`(?:\s*[
|
|
25556
|
+
const RANGE_SEP = String.raw`(?:\s*[\u2013\u2014]\s*|\s*-\s*|\s+(?:to|through|until)\s+)`;
|
|
25534
25557
|
/**
|
|
25535
25558
|
* Dates written into observation text that carry their own year, longest forms first:
|
|
25536
25559
|
* "Mar 1 - Mar 18, 2025", "May 27-28, 2023", "January 10, 2024 at 3:00 PM",
|
|
@@ -25833,15 +25856,15 @@ const SHORT_TOKEN_THRESHOLD = 3;
|
|
|
25833
25856
|
const KANA_CHARS_PER_TOKEN = 1.35;
|
|
25834
25857
|
const DEFAULT_LANGUAGE_CONFIGS = [
|
|
25835
25858
|
{
|
|
25836
|
-
pattern: /[
|
|
25859
|
+
pattern: /[\u00E4\u00F6\u00FC\u00DF\u1E9E]/i,
|
|
25837
25860
|
averageCharsPerToken: 2.6
|
|
25838
25861
|
},
|
|
25839
25862
|
{
|
|
25840
|
-
pattern: /[
|
|
25863
|
+
pattern: /[\u00E9\u00E8\u00EA\u00EB\u00E0\u00E2\u00EE\u00EF\u00F4\u00FB\u00F9\u00FC\u00FF\u00E7\u0153\u00E6\u00E1\u00ED\u00F3\u00FA\u00F1]/i,
|
|
25841
25864
|
averageCharsPerToken: 3
|
|
25842
25865
|
},
|
|
25843
25866
|
{
|
|
25844
|
-
pattern: /[
|
|
25867
|
+
pattern: /[\u0105\u0107\u0119\u0142\u0144\u00F3\u015B\u017A\u017C\u011B\u0161\u010D\u0159\u017E\u00FD\u016F\u00FA\u010F\u0165\u0148]/i,
|
|
25845
25868
|
averageCharsPerToken: 2.5
|
|
25846
25869
|
},
|
|
25847
25870
|
{
|
|
@@ -25918,7 +25941,7 @@ const OBSERVER_TOOL_ARGUMENT_MAX_DEPTH = 5;
|
|
|
25918
25941
|
const OBSERVER_TOOL_ARGUMENT_MAX_ENTRIES_PER_CONTAINER = 20;
|
|
25919
25942
|
const OBSERVER_TOOL_ARGUMENT_MAX_OUTLINE_ENTRIES = 100;
|
|
25920
25943
|
const OBSERVER_TOOL_ARGUMENT_MAX_PATH_CHARS = 160;
|
|
25921
|
-
function isObjectLike
|
|
25944
|
+
function isObjectLike(value) {
|
|
25922
25945
|
return typeof value === "object" && value !== null;
|
|
25923
25946
|
}
|
|
25924
25947
|
function sanitizeSurrogates(value) {
|
|
@@ -25930,10 +25953,10 @@ function sanitizeSurrogates(value) {
|
|
|
25930
25953
|
if (next >= 56320 && next <= 57343) {
|
|
25931
25954
|
sanitized += value.charAt(index) + value.charAt(index + 1);
|
|
25932
25955
|
index++;
|
|
25933
|
-
} else sanitized += "
|
|
25956
|
+
} else sanitized += "\uFFFD";
|
|
25934
25957
|
continue;
|
|
25935
25958
|
}
|
|
25936
|
-
sanitized += code >= 56320 && code <= 57343 ? "
|
|
25959
|
+
sanitized += code >= 56320 && code <= 57343 ? "\uFFFD" : value[index];
|
|
25937
25960
|
}
|
|
25938
25961
|
return sanitized;
|
|
25939
25962
|
}
|
|
@@ -25955,7 +25978,7 @@ function truncatePath(path) {
|
|
|
25955
25978
|
const headLength = 50;
|
|
25956
25979
|
const tailLength = 60;
|
|
25957
25980
|
const omitted = path.length - headLength - tailLength;
|
|
25958
|
-
return `${safeSlice(path, headLength)}
|
|
25981
|
+
return `${safeSlice(path, headLength)}\u2026[${omitted} chars; ${stablePathDigest(path)}]\u2026${safeTail(path, tailLength)}`;
|
|
25959
25982
|
}
|
|
25960
25983
|
function formatPath(parent, key, isArray) {
|
|
25961
25984
|
if (isArray) return truncatePath(`${parent}[${key}]`);
|
|
@@ -26064,7 +26087,7 @@ function selectOutlineEntries(entries, limits) {
|
|
|
26064
26087
|
const rendered = joinEntries(selected, marker);
|
|
26065
26088
|
if (fits(rendered, limits)) return rendered;
|
|
26066
26089
|
if (fits(marker, limits)) return marker;
|
|
26067
|
-
return fits("
|
|
26090
|
+
return fits("\u2026", limits) ? "\u2026" : "";
|
|
26068
26091
|
}
|
|
26069
26092
|
function indentPreview(value) {
|
|
26070
26093
|
return value.split("\n").map((line) => ` | ${line}`).join("\n");
|
|
@@ -26104,16 +26127,16 @@ function formatToolArgumentsForObserver(value, options) {
|
|
|
26104
26127
|
maxCharacters: options?.maxCharacters ?? Number.POSITIVE_INFINITY
|
|
26105
26128
|
};
|
|
26106
26129
|
if (limits.maxTokens <= 0 || limits.maxCharacters <= 0) return "";
|
|
26107
|
-
if (!isObjectLike
|
|
26130
|
+
if (!isObjectLike(value)) {
|
|
26108
26131
|
if (typeof value !== "string" || value.length <= OBSERVER_TOOL_ARGUMENT_INLINE_STRING_MAX_CHARS) {
|
|
26109
26132
|
const primitive = formatPrimitive(value);
|
|
26110
|
-
return fits(primitive, limits) ? primitive : fits("
|
|
26133
|
+
return fits(primitive, limits) ? primitive : fits("\u2026", limits) ? "\u2026" : "";
|
|
26111
26134
|
}
|
|
26112
26135
|
const summary = `<string, ${value.length} characters; preview size-limited>`;
|
|
26113
26136
|
const rendered = appendWithinBudget(summary, formatPreview("preview", value, limits, summary), limits);
|
|
26114
26137
|
if (rendered) return rendered;
|
|
26115
26138
|
if (fits(summary, limits)) return summary;
|
|
26116
|
-
return fits("
|
|
26139
|
+
return fits("\u2026", limits) ? "\u2026" : "";
|
|
26117
26140
|
}
|
|
26118
26141
|
const outline = [];
|
|
26119
26142
|
const previews = [];
|
|
@@ -26183,7 +26206,7 @@ function formatToolArgumentsForObserver(value, options) {
|
|
|
26183
26206
|
});
|
|
26184
26207
|
continue;
|
|
26185
26208
|
}
|
|
26186
|
-
if (!isObjectLike
|
|
26209
|
+
if (!isObjectLike(entryValue)) {
|
|
26187
26210
|
outline.push({
|
|
26188
26211
|
text: `${path}: ${formatPrimitive(entryValue)}`,
|
|
26189
26212
|
depth: current.depth,
|
|
@@ -26265,28 +26288,22 @@ function formatToolArgumentsForObserver(value, options) {
|
|
|
26265
26288
|
// src/processors/observational-memory/tool-result-helpers.ts
|
|
26266
26289
|
const ENCRYPTED_CONTENT_KEY = "encryptedContent";
|
|
26267
26290
|
const ENCRYPTED_CONTENT_REDACTION_THRESHOLD = 256;
|
|
26268
|
-
|
|
26269
|
-
|
|
26270
|
-
|
|
26271
|
-
|
|
26272
|
-
|
|
26273
|
-
|
|
26274
|
-
|
|
26275
|
-
|
|
26276
|
-
seen.set(value, sanitizedArray);
|
|
26277
|
-
for (const item of value) sanitizedArray.push(sanitizeToolResultValue(item, seen));
|
|
26278
|
-
return sanitizedArray;
|
|
26279
|
-
}
|
|
26280
|
-
const sanitizedObject = {};
|
|
26281
|
-
seen.set(value, sanitizedObject);
|
|
26282
|
-
for (const [key, entry] of Object.entries(value)) {
|
|
26283
|
-
if (key === ENCRYPTED_CONTENT_KEY && typeof entry === "string" && entry.length > ENCRYPTED_CONTENT_REDACTION_THRESHOLD) {
|
|
26284
|
-
sanitizedObject[key] = `[stripped encryptedContent: ${entry.length} characters]`;
|
|
26285
|
-
continue;
|
|
26286
|
-
}
|
|
26287
|
-
sanitizedObject[key] = sanitizeToolResultValue(entry, seen);
|
|
26291
|
+
/** The string a boxed `String` serializes to; JSON.stringify unboxes it only after the replacer has run. */
|
|
26292
|
+
function unboxedString(value) {
|
|
26293
|
+
if (typeof value === "string") return value;
|
|
26294
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
26295
|
+
try {
|
|
26296
|
+
String.prototype.valueOf.call(value);
|
|
26297
|
+
} catch {
|
|
26298
|
+
return;
|
|
26288
26299
|
}
|
|
26289
|
-
return
|
|
26300
|
+
return String(value);
|
|
26301
|
+
}
|
|
26302
|
+
/** Redacts long `encryptedContent` strings: opaque provider data that would otherwise dominate the count. */
|
|
26303
|
+
function redactEncryptedContent(key, value) {
|
|
26304
|
+
if (key !== ENCRYPTED_CONTENT_KEY) return value;
|
|
26305
|
+
const text = unboxedString(value);
|
|
26306
|
+
return text !== void 0 && text.length > ENCRYPTED_CONTENT_REDACTION_THRESHOLD ? `[stripped encryptedContent: ${text.length} characters]` : value;
|
|
26290
26307
|
}
|
|
26291
26308
|
/**
|
|
26292
26309
|
* Serializes a tool result without truncating it.
|
|
@@ -26306,14 +26323,20 @@ function serializeToolResultForTokenCounting(value) {
|
|
|
26306
26323
|
function toolErrorTextToString(errorText) {
|
|
26307
26324
|
return errorText == null ? "" : stringifyToolResult(errorText);
|
|
26308
26325
|
}
|
|
26326
|
+
/**
|
|
26327
|
+
* Serializes with `JSON.stringify` itself, the serializer storage uses, so a count of this text describes what
|
|
26328
|
+
* storage holds and a reload reads back (`toJSON()`, boxed primitives, class instances, array indices).
|
|
26329
|
+
*/
|
|
26309
26330
|
function stringifyToolResult(value) {
|
|
26310
26331
|
if (typeof value === "string") return value;
|
|
26311
|
-
|
|
26332
|
+
let json;
|
|
26312
26333
|
try {
|
|
26313
|
-
|
|
26334
|
+
json = JSON.stringify(value, redactEncryptedContent, 2);
|
|
26314
26335
|
} catch {
|
|
26315
|
-
return String(
|
|
26336
|
+
return String(value);
|
|
26316
26337
|
}
|
|
26338
|
+
if (json === void 0) return "";
|
|
26339
|
+
return json.startsWith("\"") ? JSON.parse(json) : json;
|
|
26317
26340
|
}
|
|
26318
26341
|
function resolveToolResultValue(part, invocationResult) {
|
|
26319
26342
|
const mastraMetadata = part?.providerMetadata?.mastra;
|
|
@@ -26327,13 +26350,58 @@ function resolveToolResultValue(part, invocationResult) {
|
|
|
26327
26350
|
usingStoredModelOutput: false
|
|
26328
26351
|
};
|
|
26329
26352
|
}
|
|
26353
|
+
const PREFIX_CHUNK_MIN_LENGTH = 256;
|
|
26354
|
+
function isAsciiAlphanumeric(code) {
|
|
26355
|
+
return code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122;
|
|
26356
|
+
}
|
|
26357
|
+
function isSplitWhitespace(code) {
|
|
26358
|
+
return code === 32 || code === 10 || code === 9 || code === 13;
|
|
26359
|
+
}
|
|
26360
|
+
/**
|
|
26361
|
+
* Returns a function that counts `estimateTokenCount(text.slice(0, end) + suffix)` without rescanning the
|
|
26362
|
+
* whole prefix on every call.
|
|
26363
|
+
*
|
|
26364
|
+
* tokenx splits text into segments on whitespace and punctuation runs and sums a per-segment estimate.
|
|
26365
|
+
* Letters and digits are never separators and whitespace always is, so the position between an ASCII
|
|
26366
|
+
* letter or digit and a following whitespace character is always a segment boundary: the count of any
|
|
26367
|
+
* string that shares the text up to such a position equals the count before it plus the count after it.
|
|
26368
|
+
* The text is cut at those boundaries once, and each call only rescans the chunk it ends in.
|
|
26369
|
+
*/
|
|
26370
|
+
function createPrefixTokenCounter(text) {
|
|
26371
|
+
const boundaries = [0];
|
|
26372
|
+
const tokensBefore = [0];
|
|
26373
|
+
let chunkStart = 0;
|
|
26374
|
+
let runningTokens = 0;
|
|
26375
|
+
for (let i = PREFIX_CHUNK_MIN_LENGTH; i < text.length; i++) if (i - chunkStart >= PREFIX_CHUNK_MIN_LENGTH && isSplitWhitespace(text.charCodeAt(i)) && isAsciiAlphanumeric(text.charCodeAt(i - 1))) {
|
|
26376
|
+
runningTokens += estimateTokenCount(text.slice(chunkStart, i));
|
|
26377
|
+
boundaries.push(i);
|
|
26378
|
+
tokensBefore.push(runningTokens);
|
|
26379
|
+
chunkStart = i;
|
|
26380
|
+
}
|
|
26381
|
+
return (end, suffix = "") => {
|
|
26382
|
+
let low = 0;
|
|
26383
|
+
let high = boundaries.length - 1;
|
|
26384
|
+
while (low < high) {
|
|
26385
|
+
const mid = low + high + 1 >> 1;
|
|
26386
|
+
if (boundaries[mid] <= end) low = mid;
|
|
26387
|
+
else high = mid - 1;
|
|
26388
|
+
}
|
|
26389
|
+
return tokensBefore[low] + estimateTokenCount(text.slice(boundaries[low], end) + suffix);
|
|
26390
|
+
};
|
|
26391
|
+
}
|
|
26330
26392
|
function truncateStringByTokens(text, maxTokens) {
|
|
26331
26393
|
if (!text || maxTokens <= 0) return "";
|
|
26332
|
-
const
|
|
26394
|
+
const countPrefixTokens = createPrefixTokenCounter(text);
|
|
26395
|
+
const totalTokens = countPrefixTokens(text.length);
|
|
26333
26396
|
if (totalTokens <= maxTokens) return text;
|
|
26334
26397
|
const buildCandidate = (sliceEnd) => {
|
|
26335
|
-
const
|
|
26336
|
-
|
|
26398
|
+
const visibleEnd = safeSlice(text, sliceEnd).length;
|
|
26399
|
+
const suffix = `\n... [truncated ~${totalTokens - countPrefixTokens(visibleEnd)} tokens]`;
|
|
26400
|
+
return {
|
|
26401
|
+
visibleEnd,
|
|
26402
|
+
suffix,
|
|
26403
|
+
tokens: countPrefixTokens(visibleEnd, suffix)
|
|
26404
|
+
};
|
|
26337
26405
|
};
|
|
26338
26406
|
let low = 0;
|
|
26339
26407
|
let high = text.length;
|
|
@@ -26341,12 +26409,12 @@ function truncateStringByTokens(text, maxTokens) {
|
|
|
26341
26409
|
while (low <= high) {
|
|
26342
26410
|
const mid = Math.floor((low + high) / 2);
|
|
26343
26411
|
const candidate = buildCandidate(mid);
|
|
26344
|
-
if (
|
|
26412
|
+
if (candidate.tokens <= maxTokens) {
|
|
26345
26413
|
best = candidate;
|
|
26346
26414
|
low = mid + 1;
|
|
26347
26415
|
} else high = mid - 1;
|
|
26348
26416
|
}
|
|
26349
|
-
return best;
|
|
26417
|
+
return text.slice(0, best.visibleEnd) + best.suffix;
|
|
26350
26418
|
}
|
|
26351
26419
|
function formatToolResultForObserver(value, options) {
|
|
26352
26420
|
return truncateStringByTokens(stringifyToolResult(value), options?.maxTokens ?? 5e3);
|
|
@@ -26359,24 +26427,24 @@ function formatToolResultForObserver(value, options) {
|
|
|
26359
26427
|
const OBSERVER_EXTRACTION_INSTRUCTIONS = `CRITICAL: DISTINGUISH USER ASSERTIONS FROM QUESTIONS
|
|
26360
26428
|
|
|
26361
26429
|
When the user TELLS you something about themselves, mark it as an assertion:
|
|
26362
|
-
- "I have two kids"
|
|
26363
|
-
- "I work at Acme Corp"
|
|
26364
|
-
- "I graduated in 2019"
|
|
26430
|
+
- "I have two kids" \u2192 \u{1F534} (14:30) User stated has two kids
|
|
26431
|
+
- "I work at Acme Corp" \u2192 \u{1F534} (14:31) User stated works at Acme Corp
|
|
26432
|
+
- "I graduated in 2019" \u2192 \u{1F534} (14:32) User stated graduated in 2019
|
|
26365
26433
|
|
|
26366
26434
|
When the user ASKS about something, mark it as a question/request:
|
|
26367
|
-
- "Can you help me with X?"
|
|
26368
|
-
- "What's the best way to do Y?"
|
|
26435
|
+
- "Can you help me with X?" \u2192 \u{1F534} (15:00) User asked help with X
|
|
26436
|
+
- "What's the best way to do Y?" \u2192 \u{1F534} (15:01) User asked best way to do Y
|
|
26369
26437
|
|
|
26370
26438
|
Distinguish between QUESTIONS and STATEMENTS OF INTENT:
|
|
26371
|
-
- "Can you recommend..."
|
|
26372
|
-
- "I'm looking forward to [doing X]"
|
|
26373
|
-
- "I need to [do X]"
|
|
26439
|
+
- "Can you recommend..." \u2192 Question (extract as "User asked...")
|
|
26440
|
+
- "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)")
|
|
26441
|
+
- "I need to [do X]" \u2192 Statement of intent (extract as "User stated they need to [do X] (again, add date if mentioned)")
|
|
26374
26442
|
|
|
26375
26443
|
STATE CHANGES AND UPDATES:
|
|
26376
26444
|
When a user indicates they are changing something, frame it as a state change that supersedes previous information:
|
|
26377
|
-
- "I'm going to start doing X instead of Y"
|
|
26378
|
-
- "I'm switching from A to B"
|
|
26379
|
-
- "I moved my stuff to the new place"
|
|
26445
|
+
- "I'm going to start doing X instead of Y" \u2192 "User will start doing X (changing from Y)"
|
|
26446
|
+
- "I'm switching from A to B" \u2192 "User is switching from A to B"
|
|
26447
|
+
- "I moved my stuff to the new place" \u2192 "User moved their stuff to the new place (no longer at previous location)"
|
|
26380
26448
|
|
|
26381
26449
|
If the new state contradicts or updates previous information, make that explicit:
|
|
26382
26450
|
- BAD: "User plans to use the new method"
|
|
@@ -26467,11 +26535,11 @@ BAD: User got something.
|
|
|
26467
26535
|
GOOD: User purchased / received / was given something. (be specific)
|
|
26468
26536
|
|
|
26469
26537
|
Common clarifications:
|
|
26470
|
-
- "getting" something regularly
|
|
26471
|
-
- "getting" something once
|
|
26472
|
-
- "got"
|
|
26473
|
-
- "signed up"
|
|
26474
|
-
- "stopped getting"
|
|
26538
|
+
- "getting" something regularly \u2192 "subscribed to" or "enrolled in"
|
|
26539
|
+
- "getting" something once \u2192 "purchased" or "acquired"
|
|
26540
|
+
- "got" \u2192 "purchased", "received as gift", "was given", "picked up"
|
|
26541
|
+
- "signed up" \u2192 "enrolled in", "registered for", "subscribed to"
|
|
26542
|
+
- "stopped getting" \u2192 "canceled", "unsubscribed from", "discontinued"
|
|
26475
26543
|
|
|
26476
26544
|
When the assistant interprets or confirms the user's vague language, prefer the assistant's precise terminology.
|
|
26477
26545
|
|
|
@@ -26556,16 +26624,16 @@ AVOIDING REPETITIVE OBSERVATIONS:
|
|
|
26556
26624
|
- Do NOT repeat the same observation across multiple turns if there is no new information.
|
|
26557
26625
|
- 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.
|
|
26558
26626
|
|
|
26559
|
-
Example
|
|
26560
|
-
*
|
|
26561
|
-
*
|
|
26562
|
-
*
|
|
26627
|
+
Example \u2014 BAD (repetitive):
|
|
26628
|
+
* \u{1F7E1} (14:30) Agent used view tool on src/auth.ts
|
|
26629
|
+
* \u{1F7E1} (14:31) Agent used view tool on src/users.ts
|
|
26630
|
+
* \u{1F7E1} (14:32) Agent used view tool on src/routes.ts
|
|
26563
26631
|
|
|
26564
|
-
Example
|
|
26565
|
-
*
|
|
26566
|
-
* -> viewed src/auth.ts
|
|
26567
|
-
* -> viewed src/users.ts
|
|
26568
|
-
* -> viewed src/routes.ts
|
|
26632
|
+
Example \u2014 GOOD (grouped):
|
|
26633
|
+
* \u{1F7E1} (14:30) Agent browsed source files for auth flow
|
|
26634
|
+
* -> viewed src/auth.ts \u2014 found token validation logic
|
|
26635
|
+
* -> viewed src/users.ts \u2014 found user lookup by email
|
|
26636
|
+
* -> viewed src/routes.ts \u2014 found middleware chain
|
|
26569
26637
|
|
|
26570
26638
|
Only add a new observation for a repeated action if the NEW result changes the picture.
|
|
26571
26639
|
|
|
@@ -26578,29 +26646,29 @@ COMPLETION TRACKING:
|
|
|
26578
26646
|
Completion observations are not just summaries. They are explicit memory signals to the assistant that a task, question, or subtask has been resolved.
|
|
26579
26647
|
Without clear completion markers, the assistant may forget that work is already finished and may repeat, reopen, or continue an already-completed task.
|
|
26580
26648
|
|
|
26581
|
-
Use
|
|
26649
|
+
Use \u2705 to answer: "What exactly is now done?"
|
|
26582
26650
|
Choose completion observations that help the assistant know what is finished and should not be reworked unless new information appears.
|
|
26583
26651
|
|
|
26584
|
-
Use
|
|
26652
|
+
Use \u2705 when:
|
|
26585
26653
|
- The user explicitly confirms something worked or was answered ("thanks, that fixed it", "got it", "perfect")
|
|
26586
26654
|
- The assistant provided a definitive, complete answer to a factual question and the user moved on
|
|
26587
26655
|
- A multi-step task reached its stated goal
|
|
26588
26656
|
- The user acknowledged receipt of requested information
|
|
26589
26657
|
- A concrete subtask, fix, deliverable, or implementation step became complete during ongoing work
|
|
26590
26658
|
|
|
26591
|
-
Do NOT use
|
|
26592
|
-
- The assistant merely responded
|
|
26659
|
+
Do NOT use \u2705 when:
|
|
26660
|
+
- The assistant merely responded \u2014 the user might follow up with corrections
|
|
26593
26661
|
- The topic is paused but not resolved ("I'll try that later")
|
|
26594
26662
|
- The user's reaction is ambiguous
|
|
26595
26663
|
|
|
26596
26664
|
FORMAT:
|
|
26597
26665
|
As a sub-bullet under the related observation group:
|
|
26598
|
-
*
|
|
26666
|
+
* \u{1F534} (14:30) User asked how to configure auth middleware
|
|
26599
26667
|
* -> Agent explained JWT setup with code example
|
|
26600
|
-
*
|
|
26668
|
+
* \u2705 User confirmed auth is working
|
|
26601
26669
|
|
|
26602
26670
|
Or as a standalone observation when closing out a broader task:
|
|
26603
|
-
*
|
|
26671
|
+
* \u2705 (14:45) Auth configuration task completed \u2014 user confirmed middleware is working
|
|
26604
26672
|
|
|
26605
26673
|
Completion observations should be terse but specific about WHAT was completed.
|
|
26606
26674
|
Prefer concrete resolved outcomes over abstract workflow status so the assistant remembers what is already done.`;
|
|
@@ -26617,28 +26685,28 @@ buildObserverOutputFormat();
|
|
|
26617
26685
|
*/
|
|
26618
26686
|
function buildObserverOutputFormat(extractors) {
|
|
26619
26687
|
return `Use priority levels:
|
|
26620
|
-
-
|
|
26621
|
-
-
|
|
26622
|
-
-
|
|
26623
|
-
-
|
|
26688
|
+
- \u{1F534} High: explicit user facts, preferences, unresolved goals, critical context
|
|
26689
|
+
- \u{1F7E1} Medium: project details, learned information, tool results
|
|
26690
|
+
- \u{1F7E2} Low: minor details, uncertain observations
|
|
26691
|
+
- \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
|
|
26624
26692
|
|
|
26625
26693
|
Group related observations (like tool sequences) by indenting:
|
|
26626
|
-
*
|
|
26694
|
+
* \u{1F534} (14:33) Agent debugging auth issue
|
|
26627
26695
|
* -> ran git status, found 3 modified files
|
|
26628
26696
|
* -> viewed auth.ts:45-60, found missing null check
|
|
26629
26697
|
* -> applied fix, tests now pass
|
|
26630
|
-
*
|
|
26698
|
+
* \u2705 Tests passing, auth issue resolved
|
|
26631
26699
|
|
|
26632
26700
|
Group observations by date. Within a date, list observations in the order the events happened (not by importance), each with 24-hour time.
|
|
26633
26701
|
|
|
26634
26702
|
<observations>
|
|
26635
26703
|
Date: Dec 4, 2025
|
|
26636
|
-
*
|
|
26637
|
-
*
|
|
26638
|
-
*
|
|
26704
|
+
* \u{1F534} (14:30) User prefers direct answers
|
|
26705
|
+
* \u{1F534} (14:31) Working on feature X
|
|
26706
|
+
* \u{1F7E1} (14:32) User might prefer dark mode
|
|
26639
26707
|
|
|
26640
26708
|
Date: Dec 5, 2025
|
|
26641
|
-
*
|
|
26709
|
+
* \u{1F534} (09:15) Continued work on feature X
|
|
26642
26710
|
</observations>
|
|
26643
26711
|
|
|
26644
26712
|
${buildExtractorOutputSections(extractors ?? []) || (extractors === void 0 ? `
|
|
@@ -26668,9 +26736,9 @@ const OBSERVER_GUIDELINES = `- Be specific enough for the assistant to act on
|
|
|
26668
26736
|
- If the agent calls tools, observe what was called, why, and what was learned
|
|
26669
26737
|
- When observing files with line numbers, include the line number if useful
|
|
26670
26738
|
- If the agent provides a detailed response, observe the contents so it could be repeated
|
|
26671
|
-
- Make sure you start each observation with a priority emoji (
|
|
26672
|
-
- Capture the user's words closely
|
|
26673
|
-
- Treat
|
|
26739
|
+
- Make sure you start each observation with a priority emoji (\u{1F534}, \u{1F7E1}, \u{1F7E2}) or a completion marker (\u2705)
|
|
26740
|
+
- 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}
|
|
26741
|
+
- Treat \u2705 as a memory signal that tells the assistant something is finished and should not be repeated unless new information changes it
|
|
26674
26742
|
- Make completion observations answer "What exactly is now done?"
|
|
26675
26743
|
- Prefer concrete resolved outcomes over meta-level workflow or bookkeeping updates
|
|
26676
26744
|
- When multiple concrete things were completed, capture the concrete completed work rather than collapsing it into a vague progress summary
|
|
@@ -26724,8 +26792,8 @@ For multi-thread output, wrap each thread's observations like this:
|
|
|
26724
26792
|
<observations>
|
|
26725
26793
|
<thread id="thread_id_1">
|
|
26726
26794
|
Date: Dec 4, 2025
|
|
26727
|
-
*
|
|
26728
|
-
*
|
|
26795
|
+
* \u{1F534} (14:30) User prefers direct answers
|
|
26796
|
+
* \u{1F534} (14:31) Working on feature X${currentTaskEnabled ? `
|
|
26729
26797
|
|
|
26730
26798
|
<current-task>
|
|
26731
26799
|
What the agent is currently working on in this thread
|
|
@@ -26738,7 +26806,7 @@ Hint for the agent's next message in this thread
|
|
|
26738
26806
|
|
|
26739
26807
|
<thread id="thread_id_2">
|
|
26740
26808
|
Date: Dec 5, 2025
|
|
26741
|
-
*
|
|
26809
|
+
* \u{1F534} (09:15) User asked about deployment${currentTaskEnabled ? `
|
|
26742
26810
|
|
|
26743
26811
|
<current-task>
|
|
26744
26812
|
Current task for this thread
|
|
@@ -27586,7 +27654,7 @@ function sanitizeObservationLines(observations) {
|
|
|
27586
27654
|
const lines = observations.split("\n");
|
|
27587
27655
|
let changed = false;
|
|
27588
27656
|
for (let i = 0; i < lines.length; i++) if (lines[i].length > MAX_OBSERVATION_LINE_CHARS) {
|
|
27589
|
-
lines[i] = safeSlice(lines[i], MAX_OBSERVATION_LINE_CHARS) + "
|
|
27657
|
+
lines[i] = safeSlice(lines[i], MAX_OBSERVATION_LINE_CHARS) + " \u2026 [truncated]";
|
|
27590
27658
|
changed = true;
|
|
27591
27659
|
}
|
|
27592
27660
|
return changed ? lines.join("\n") : observations;
|
|
@@ -27810,8 +27878,8 @@ function extractCurrentTask(observations) {
|
|
|
27810
27878
|
*/
|
|
27811
27879
|
function optimizeObservationsForContext(observations) {
|
|
27812
27880
|
let optimized = stripEphemeralAnchorIds(observations);
|
|
27813
|
-
optimized = optimized.replace(
|
|
27814
|
-
optimized = optimized.replace(
|
|
27881
|
+
optimized = optimized.replace(/\uD83D\uDFE1\s*/g, "");
|
|
27882
|
+
optimized = optimized.replace(/\uD83D\uDFE2\s*/g, "");
|
|
27815
27883
|
optimized = optimized.replace(/\s*->\s*/g, " ");
|
|
27816
27884
|
optimized = optimized.replace(/ +/g, " ");
|
|
27817
27885
|
optimized = optimized.replace(/\n{3,}/g, "\n\n");
|
|
@@ -28612,9 +28680,24 @@ function mergeCacheEntry(cache, key, entry) {
|
|
|
28612
28680
|
function getPartCacheEntry(part, key) {
|
|
28613
28681
|
return getCacheEntry(getPartMastraMetadata(part)?.tokenEstimate, key);
|
|
28614
28682
|
}
|
|
28683
|
+
/**
|
|
28684
|
+
* Parts this process gave a new stored count. A part loaded from storage with its count is never in here,
|
|
28685
|
+
* so a message holding one of these parts has a count storage does not have yet.
|
|
28686
|
+
*/
|
|
28687
|
+
const partsWithUnsavedCount = /* @__PURE__ */ new WeakSet();
|
|
28688
|
+
/** Whether `part` gained a stored count in this process that has not been handed to a save yet. */
|
|
28689
|
+
function hasUnsavedTokenEstimate(part) {
|
|
28690
|
+
return typeof part === "object" && part !== null && partsWithUnsavedCount.has(part);
|
|
28691
|
+
}
|
|
28692
|
+
/** Note that `part`'s count is on its way to storage, so later steps do not save it again. */
|
|
28693
|
+
function markTokenEstimateSaved(part) {
|
|
28694
|
+
if (typeof part === "object" && part !== null) partsWithUnsavedCount.delete(part);
|
|
28695
|
+
}
|
|
28696
|
+
const partCountMemo = /* @__PURE__ */ new WeakMap();
|
|
28615
28697
|
function setPartCacheEntry(part, key, entry) {
|
|
28616
28698
|
const mastraMetadata = ensurePartMastraMetadata(part);
|
|
28617
28699
|
mastraMetadata.tokenEstimate = mergeCacheEntry(mastraMetadata.tokenEstimate, key, entry);
|
|
28700
|
+
partsWithUnsavedCount.add(part);
|
|
28618
28701
|
}
|
|
28619
28702
|
/**
|
|
28620
28703
|
* Extracts a caller-supplied token estimate stamped on a part via
|
|
@@ -29308,14 +29391,19 @@ async function fetchGoogleAttachmentTokenEstimate(modelId, part) {
|
|
|
29308
29391
|
* undercounted as generic JSON blobs.
|
|
29309
29392
|
*/
|
|
29310
29393
|
var TokenCounter = class TokenCounter {
|
|
29311
|
-
|
|
29394
|
+
/**
|
|
29395
|
+
* Stored counts belong to the stock estimator. A subclass or instance that overrides `countString`
|
|
29396
|
+
* reads and writes its own namespace, so it never reuses a count the stock estimator saved.
|
|
29397
|
+
*/
|
|
29398
|
+
get cacheSource() {
|
|
29399
|
+
return this.countString === TokenCounter.prototype.countString ? `v${TOKEN_ESTIMATE_CACHE_VERSION}:${resolveEstimatorId()}` : `v${TOKEN_ESTIMATE_CACHE_VERSION}:custom`;
|
|
29400
|
+
}
|
|
29312
29401
|
defaultModelContext;
|
|
29313
29402
|
inFlightAttachmentCounts = /* @__PURE__ */ new Map();
|
|
29314
29403
|
multimodalToolResultCounts = /* @__PURE__ */ new WeakMap();
|
|
29315
29404
|
static TOKENS_PER_MESSAGE = 3.8;
|
|
29316
29405
|
static TOKENS_PER_CONVERSATION = 24;
|
|
29317
29406
|
constructor(options) {
|
|
29318
|
-
this.cacheSource = `v${TOKEN_ESTIMATE_CACHE_VERSION}:${resolveEstimatorId()}`;
|
|
29319
29407
|
this.defaultModelContext = parseModelContext(options?.model);
|
|
29320
29408
|
}
|
|
29321
29409
|
runWithModelContext(model, fn) {
|
|
@@ -29346,6 +29434,28 @@ var TokenCounter = class TokenCounter {
|
|
|
29346
29434
|
});
|
|
29347
29435
|
return tokens;
|
|
29348
29436
|
}
|
|
29437
|
+
/**
|
|
29438
|
+
* Count one content-only piece of a part (its text, a tool's args or result) the same way as
|
|
29439
|
+
* {@link readOrPersistPartEstimate}: a stored count is reused only when its content hash matches.
|
|
29440
|
+
* `refs` are the values the payload is built from. While the same part object still holds the same
|
|
29441
|
+
* refs, the count from the last call is returned without serializing or hashing again, so a part
|
|
29442
|
+
* counted by `getStatus` and then by the next step is hashed once per process.
|
|
29443
|
+
* Only string refs are memoized (object payloads are hashed every time, since they can change in place).
|
|
29444
|
+
*/
|
|
29445
|
+
readOrPersistMemoizedPartEstimate(part, kind, refs, getPayload) {
|
|
29446
|
+
if (!refs.every((ref) => typeof ref === "string")) return this.readOrPersistPartEstimate(part, kind, getPayload());
|
|
29447
|
+
let byKind = partCountMemo.get(part);
|
|
29448
|
+
const memo = byKind?.get(kind);
|
|
29449
|
+
if (memo && memo.owner === this && memo.refs.length === refs.length && memo.refs.every((ref, i) => ref === refs[i])) return memo.tokens;
|
|
29450
|
+
const tokens = this.readOrPersistPartEstimate(part, kind, getPayload());
|
|
29451
|
+
if (!byKind) partCountMemo.set(part, byKind = /* @__PURE__ */ new Map());
|
|
29452
|
+
byKind.set(kind, {
|
|
29453
|
+
owner: this,
|
|
29454
|
+
refs,
|
|
29455
|
+
tokens
|
|
29456
|
+
});
|
|
29457
|
+
return tokens;
|
|
29458
|
+
}
|
|
29349
29459
|
readOrPersistFixedPartEstimate(part, kind, payload, tokens) {
|
|
29350
29460
|
const key = buildEstimateKey(kind, payload);
|
|
29351
29461
|
const cached = getPartCacheEntry(part, key);
|
|
@@ -29696,18 +29806,23 @@ var TokenCounter = class TokenCounter {
|
|
|
29696
29806
|
/**
|
|
29697
29807
|
* Count the name and the arguments of a tool call. Every state before the tool produces an
|
|
29698
29808
|
* output holds the same call signature in the context window, so all of those states share
|
|
29699
|
-
* these cache kinds
|
|
29700
|
-
*
|
|
29809
|
+
* these cache kinds, and the estimate stays warm while the invocation moves from one state to
|
|
29810
|
+
* the next. Name and args don't change across those states once the call stops streaming.
|
|
29701
29811
|
*/
|
|
29702
29812
|
countToolCallSignature(part, invocation) {
|
|
29703
29813
|
let tokens = 0;
|
|
29704
29814
|
let overheadDelta = 0;
|
|
29705
|
-
|
|
29815
|
+
const storable = invocation.state !== "partial-call";
|
|
29816
|
+
const count = (kind, ref, getPayload) => storable ? this.readOrPersistMemoizedPartEstimate(part, kind, [ref], getPayload) : this.readOrPersistPartEstimate(part, kind, getPayload());
|
|
29817
|
+
if (invocation.toolName) {
|
|
29818
|
+
const toolName = invocation.toolName;
|
|
29819
|
+
tokens += count("tool-call-name", toolName, () => toolName);
|
|
29820
|
+
}
|
|
29706
29821
|
if (invocation.args !== void 0) {
|
|
29707
|
-
|
|
29822
|
+
const args = invocation.args;
|
|
29823
|
+
if (typeof args === "string") tokens += count("tool-call-args", args, () => args);
|
|
29708
29824
|
else {
|
|
29709
|
-
|
|
29710
|
-
tokens += this.readOrPersistPartEstimate(part, "tool-call-args-json", argsJson);
|
|
29825
|
+
tokens += count("tool-call-args-json", args, () => JSON.stringify(args));
|
|
29711
29826
|
overheadDelta -= 12;
|
|
29712
29827
|
}
|
|
29713
29828
|
}
|
|
@@ -29719,11 +29834,14 @@ var TokenCounter = class TokenCounter {
|
|
|
29719
29834
|
countNonAttachmentPart(part) {
|
|
29720
29835
|
let overheadDelta = 0;
|
|
29721
29836
|
let extraMessageDelta = 0;
|
|
29722
|
-
if (part.type === "text")
|
|
29723
|
-
|
|
29724
|
-
|
|
29725
|
-
|
|
29726
|
-
|
|
29837
|
+
if (part.type === "text") {
|
|
29838
|
+
const text = part.text;
|
|
29839
|
+
return {
|
|
29840
|
+
tokens: this.readOrPersistMemoizedPartEstimate(part, "text", [text], () => text),
|
|
29841
|
+
overheadDelta,
|
|
29842
|
+
extraMessageDelta
|
|
29843
|
+
};
|
|
29844
|
+
}
|
|
29727
29845
|
if (part.type === "tool-invocation") {
|
|
29728
29846
|
const invocation = part.toolInvocation;
|
|
29729
29847
|
const state = invocation.state;
|
|
@@ -29742,7 +29860,7 @@ var TokenCounter = class TokenCounter {
|
|
|
29742
29860
|
tokens += signature.tokens;
|
|
29743
29861
|
overheadDelta += signature.overheadDelta;
|
|
29744
29862
|
const reason = invocation.approval?.reason;
|
|
29745
|
-
if (reason) tokens += this.
|
|
29863
|
+
if (reason) tokens += this.readOrPersistMemoizedPartEstimate(part, "tool-approval-reason", [reason], () => reason);
|
|
29746
29864
|
return {
|
|
29747
29865
|
tokens,
|
|
29748
29866
|
overheadDelta,
|
|
@@ -29758,15 +29876,12 @@ var TokenCounter = class TokenCounter {
|
|
|
29758
29876
|
if (resultForCounting !== void 0 && (typeof resultForCounting !== "string" || resultForCounting.trim().length > 0)) {
|
|
29759
29877
|
const contentTokens = this.countMultimodalToolResultContent(part, resultForCounting);
|
|
29760
29878
|
if (contentTokens !== void 0) tokens += contentTokens;
|
|
29761
|
-
else
|
|
29762
|
-
const formattedResult = serializeToolResultForTokenCounting(resultForCounting);
|
|
29763
|
-
tokens += this.readOrPersistPartEstimate(part, usingStoredModelOutput ? "tool-result-model-output-json" : "tool-result-json", formattedResult);
|
|
29764
|
-
}
|
|
29879
|
+
else tokens += this.readOrPersistMemoizedPartEstimate(part, usingStoredModelOutput ? "tool-result-model-output-json" : "tool-result-json", [resultForCounting], () => serializeToolResultForTokenCounting(resultForCounting));
|
|
29765
29880
|
if (typeof resultForCounting !== "string") overheadDelta -= 12;
|
|
29766
29881
|
} else {
|
|
29767
29882
|
const errorText = toolErrorTextToString(invocation.errorText);
|
|
29768
29883
|
const fallback = invocation.isError ? errorText.trim() ? errorText : "Tool execution failed" : "[empty result]";
|
|
29769
|
-
tokens += this.
|
|
29884
|
+
tokens += this.readOrPersistMemoizedPartEstimate(part, invocation.isError ? "tool-result-error" : "tool-result-json", [fallback], () => fallback);
|
|
29770
29885
|
}
|
|
29771
29886
|
return {
|
|
29772
29887
|
tokens,
|
|
@@ -29780,7 +29895,7 @@ var TokenCounter = class TokenCounter {
|
|
|
29780
29895
|
tokens += signature.tokens;
|
|
29781
29896
|
overheadDelta += signature.overheadDelta;
|
|
29782
29897
|
const reason = invocation.approval?.reason?.trim() ? invocation.approval.reason : "Tool call was not approved by the user";
|
|
29783
|
-
tokens += this.
|
|
29898
|
+
tokens += this.readOrPersistMemoizedPartEstimate(part, "tool-result-denied", [reason], () => reason);
|
|
29784
29899
|
return {
|
|
29785
29900
|
tokens,
|
|
29786
29901
|
overheadDelta,
|
|
@@ -29794,7 +29909,7 @@ var TokenCounter = class TokenCounter {
|
|
|
29794
29909
|
overheadDelta += signature.overheadDelta;
|
|
29795
29910
|
const errorText = toolErrorTextToString(invocation.errorText);
|
|
29796
29911
|
const errorMessage = errorText.trim() ? errorText : "Tool execution failed";
|
|
29797
|
-
tokens += this.
|
|
29912
|
+
tokens += this.readOrPersistMemoizedPartEstimate(part, "tool-result-error", [errorMessage], () => errorMessage);
|
|
29798
29913
|
return {
|
|
29799
29914
|
tokens,
|
|
29800
29915
|
overheadDelta,
|
|
@@ -29807,6 +29922,11 @@ var TokenCounter = class TokenCounter {
|
|
|
29807
29922
|
overheadDelta,
|
|
29808
29923
|
extraMessageDelta
|
|
29809
29924
|
};
|
|
29925
|
+
if (part.type === "step-start") return {
|
|
29926
|
+
tokens: 0,
|
|
29927
|
+
overheadDelta,
|
|
29928
|
+
extraMessageDelta
|
|
29929
|
+
};
|
|
29810
29930
|
if (part.type === "reasoning") return {
|
|
29811
29931
|
tokens: 0,
|
|
29812
29932
|
overheadDelta,
|
|
@@ -30097,8 +30217,8 @@ const updateWorkingMemoryTool = (memoryConfig) => {
|
|
|
30097
30217
|
}
|
|
30098
30218
|
const usesMergeSemantics = Boolean(schema);
|
|
30099
30219
|
const useStateSignals = memoryConfig?.workingMemory?.useStateSignals === true;
|
|
30100
|
-
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
|
|
30101
|
-
const description = schema ? useStateSignals ? `${stateSignalsPreamble} Data is merged with existing memory
|
|
30220
|
+
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.`;
|
|
30221
|
+
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.`;
|
|
30102
30222
|
return createTool({
|
|
30103
30223
|
id: "update-working-memory",
|
|
30104
30224
|
description,
|
|
@@ -31129,8 +31249,8 @@ async function pageGroups({ om, threadId, resourceId, groupId, recordId, directi
|
|
|
31129
31249
|
})).count > 0;
|
|
31130
31250
|
const hasLater = direction === "before" || hasMore;
|
|
31131
31251
|
const newer = hasLater ? null : await newerMessagesNote(page.at(-1).group, countNewerMessages, pagingThreadId);
|
|
31132
|
-
text.unshift(hasEarlier ?
|
|
31133
|
-
text.push(hasLater ?
|
|
31252
|
+
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");
|
|
31253
|
+
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");
|
|
31134
31254
|
text.unshift(`### Observation page\nThread: ${threadTitle || "(untitled)"}\nShowing ${page.length} groups ${requestedDirection === void 0 ? "starting at" : `strictly ${direction}`} \`${groupId}\` (oldest first).`);
|
|
31135
31255
|
return {
|
|
31136
31256
|
results: text.join("\n\n"),
|
|
@@ -31318,7 +31438,7 @@ async function listThreadsForResource({ memory, resourceId, currentThreadId, pag
|
|
|
31318
31438
|
const title = thread.title || "(untitled)";
|
|
31319
31439
|
const updated = formatTimestamp(thread.updatedAt);
|
|
31320
31440
|
const created = formatTimestamp(thread.createdAt);
|
|
31321
|
-
const marker = isCurrent ? "
|
|
31441
|
+
const marker = isCurrent ? " \u2190 current" : "";
|
|
31322
31442
|
lines.push(`- **${title}**${marker}`);
|
|
31323
31443
|
lines.push(` id: ${thread.id}`);
|
|
31324
31444
|
lines.push(` updated: ${updated} | created: ${created}`);
|
|
@@ -31497,7 +31617,7 @@ async function searchMessagesForResource({ memory, om, resourceId, currentThread
|
|
|
31497
31617
|
const groupLine = match.groupId ? `- observation group: ${groupCursor(match.groupId, match.recordId)}` : void 0;
|
|
31498
31618
|
const scoreLine = `- score: ${match.score.toFixed(2)}`;
|
|
31499
31619
|
const prev = i > 0 ? ordered[i - 1].match : void 0;
|
|
31500
|
-
if (om && prev?.groupId && match.groupId && prev.threadId === match.threadId) sections.push(
|
|
31620
|
+
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`);
|
|
31501
31621
|
if (suppression) {
|
|
31502
31622
|
sections.push(`${groupLine}\n thread: ${match.threadId}; ${suppression}`);
|
|
31503
31623
|
continue;
|
|
@@ -32052,7 +32172,7 @@ async function recallAttachmentView({ memory, threadId, resourceId, cursor, part
|
|
|
32052
32172
|
const partType = rawPart?.type;
|
|
32053
32173
|
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.` };
|
|
32054
32174
|
const resolvedAttachment = resolveViewableAttachment(rawPart);
|
|
32055
|
-
if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)}
|
|
32175
|
+
if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)} \u2014 ${resolvedAttachment.note}` };
|
|
32056
32176
|
return { content: [{
|
|
32057
32177
|
type: "text",
|
|
32058
32178
|
text: formatAttachmentPart(partType, rawPart)
|
|
@@ -32455,7 +32575,7 @@ const recallTool = (_memoryConfig, options) => {
|
|
|
32455
32575
|
if (!thread) return { error: "Could not resolve current thread." };
|
|
32456
32576
|
if (isResourceScope && resourceId && thread.resourceId !== resourceId) throw new Error("Thread does not belong to the active resource");
|
|
32457
32577
|
return {
|
|
32458
|
-
threads: `- **${thread.title || "(untitled)"}**
|
|
32578
|
+
threads: `- **${thread.title || "(untitled)"}** \u2190 current\n id: ${thread.id}\n updated: ${formatTimestamp(thread.updatedAt)} | created: ${formatTimestamp(thread.createdAt)}`,
|
|
32459
32579
|
count: 1,
|
|
32460
32580
|
page: 0,
|
|
32461
32581
|
hasMore: false
|
|
@@ -33215,9 +33335,10 @@ const suggestedResponseInstructions = `Hint for the agent's immediate next messa
|
|
|
33215
33335
|
- "The assistant should wait for the user to respond before continuing."
|
|
33216
33336
|
- Call the view tool on src/example.ts to continue debugging.`;
|
|
33217
33337
|
const threadTitleInstructions = `A short, noun-phrase title for this conversation (2-5 words). Examples:
|
|
33218
|
-
- "Auth bug fix"
|
|
33219
|
-
- "Dark mode toggle"
|
|
33220
|
-
- "Deployment pipeline setup"
|
|
33338
|
+
- "Auth bug fix" \u2014 not "Fixing the auth bug"
|
|
33339
|
+
- "Dark mode toggle" \u2014 not "User wants dark mode toggle added"
|
|
33340
|
+
- "Deployment pipeline setup" \u2014 not "Setting up deployment pipeline for project"
|
|
33341
|
+
Write the title in the same language the user's messages are written in.
|
|
33221
33342
|
Only update when the topic meaningfully changes.`;
|
|
33222
33343
|
function createCurrentTaskExtractor() {
|
|
33223
33344
|
return new Extractor({
|
|
@@ -34294,7 +34415,7 @@ var SyncObservationStrategy = class extends ObservationStrategy {
|
|
|
34294
34415
|
failures: result.extractionFailures,
|
|
34295
34416
|
previousValues: this.priorExtractedValues,
|
|
34296
34417
|
rawObservations: result.observations,
|
|
34297
|
-
recentMessages: formatMessagesForObserver(this.opts.messages, {
|
|
34418
|
+
recentMessages: () => formatMessagesForObserver(this.opts.messages, {
|
|
34298
34419
|
maxPartLength: 500,
|
|
34299
34420
|
timeZone: this.opts.record.observedTimezone
|
|
34300
34421
|
}),
|
|
@@ -34519,7 +34640,7 @@ var AsyncBufferObservationStrategy = class extends ObservationStrategy {
|
|
|
34519
34640
|
failures: result.extractionFailures,
|
|
34520
34641
|
previousValues: this.priorExtractedValues,
|
|
34521
34642
|
rawObservations: result.observations,
|
|
34522
|
-
recentMessages: formatMessagesForObserver(messages, {
|
|
34643
|
+
recentMessages: () => formatMessagesForObserver(messages, {
|
|
34523
34644
|
maxPartLength: 500,
|
|
34524
34645
|
timeZone: this.opts.record.observedTimezone
|
|
34525
34646
|
}),
|
|
@@ -34949,7 +35070,7 @@ var ResourceScopedObservationStrategy = class extends ObservationStrategy {
|
|
|
34949
35070
|
failures: result.extractionFailures,
|
|
34950
35071
|
previousValues,
|
|
34951
35072
|
rawObservations: result.observations,
|
|
34952
|
-
recentMessages: formatMessagesForObserver(threadMessages, {
|
|
35073
|
+
recentMessages: () => formatMessagesForObserver(threadMessages, {
|
|
34953
35074
|
maxPartLength: 500,
|
|
34954
35075
|
timeZone: this.opts.record.observedTimezone
|
|
34955
35076
|
}),
|
|
@@ -35179,6 +35300,47 @@ ObservationStrategy.create = ((om, opts) => {
|
|
|
35179
35300
|
if (deps.scope === "resource" && opts.resourceId) return new ResourceScopedObservationStrategy(deps, opts);
|
|
35180
35301
|
return new SyncObservationStrategy(deps, opts);
|
|
35181
35302
|
});
|
|
35303
|
+
// src/processors/observational-memory/resave-counted-messages.ts
|
|
35304
|
+
/**
|
|
35305
|
+
* Mark the stored history of `threadId` in `messageList` that OM gave new token counts, so the counts are saved
|
|
35306
|
+
* with the messages. Call the returned function once the counting is done: every message holding a part that
|
|
35307
|
+
* gained a count in this process is marked for resave, and the normal save writes it back whole. Counts made
|
|
35308
|
+
* before this is called (while the turn loaded history) are caught too.
|
|
35309
|
+
*
|
|
35310
|
+
* Only messages of `threadId` are marked. A message recalled from another thread of the resource is counted but
|
|
35311
|
+
* never written, because saving it would bump that thread's `updatedAt` and reorder the recent-thread list.
|
|
35312
|
+
*
|
|
35313
|
+
* A Core without `markForResave` is left alone: counting still works, the counts are just not saved.
|
|
35314
|
+
*/
|
|
35315
|
+
function resaveCountedMessagesFor(messageList, threadId) {
|
|
35316
|
+
if (typeof messageList.markForResave !== "function") return () => {};
|
|
35317
|
+
return () => {
|
|
35318
|
+
for (const message of messageList.get.remembered.db()) {
|
|
35319
|
+
if (message.threadId !== threadId) continue;
|
|
35320
|
+
const parts = message.content?.parts ?? [];
|
|
35321
|
+
if (!parts.some(hasUnsavedTokenEstimate)) continue;
|
|
35322
|
+
messageList.markForResave(message);
|
|
35323
|
+
parts.forEach(markTokenEstimateSaved);
|
|
35324
|
+
}
|
|
35325
|
+
};
|
|
35326
|
+
}
|
|
35327
|
+
/** The stored messages marked for resave in `messageList`; none for a Core without `markForResave`. */
|
|
35328
|
+
function messagesMarkedForResave(messageList) {
|
|
35329
|
+
return typeof messageList.getMessagesToResave === "function" ? messageList.getMessagesToResave() : [];
|
|
35330
|
+
}
|
|
35331
|
+
/**
|
|
35332
|
+
* Ids of the stored messages marked for resave in `messageList` that are not in `ownMessages` (the turn's
|
|
35333
|
+
* own input and output). Those are saved whole; the rest only gained counts and are patched onto storage.
|
|
35334
|
+
*/
|
|
35335
|
+
function idsMarkedForResave(messageList, ownMessages = []) {
|
|
35336
|
+
const own = new Set(ownMessages.map((message) => message.id));
|
|
35337
|
+
return new Set(messagesMarkedForResave(messageList).map((message) => message.id).filter((id) => !own.has(id)));
|
|
35338
|
+
}
|
|
35339
|
+
/** `messages` with the messages marked for resave added, each message once. */
|
|
35340
|
+
function withMessagesMarkedForResave(messageList, messages) {
|
|
35341
|
+
const ids = new Set(messages.map((message) => message.id));
|
|
35342
|
+
return [...messages, ...messagesMarkedForResave(messageList).filter((message) => !ids.has(message.id))];
|
|
35343
|
+
}
|
|
35182
35344
|
// src/processors/observational-memory/observation-turn/load-memory-context.ts
|
|
35183
35345
|
async function loadMemoryContextMessages({ memory, messageList, threadId, resourceId, runState }) {
|
|
35184
35346
|
const ctx = await memory.getContext({
|
|
@@ -35186,7 +35348,8 @@ async function loadMemoryContextMessages({ memory, messageList, threadId, resour
|
|
|
35186
35348
|
resourceId,
|
|
35187
35349
|
runState
|
|
35188
35350
|
});
|
|
35189
|
-
|
|
35351
|
+
const messages = ctx.messages.filter((msg) => msg.role !== "system");
|
|
35352
|
+
if (messages.length) messageList.add(messages, "memory");
|
|
35190
35353
|
return ctx;
|
|
35191
35354
|
}
|
|
35192
35355
|
// src/processors/observational-memory/observation-turn/safe-buffer-prefix.ts
|
|
@@ -35282,7 +35445,7 @@ var ObservationStep = class {
|
|
|
35282
35445
|
}
|
|
35283
35446
|
/** Step context from prepare(). Throws if prepare() hasn't been called. */
|
|
35284
35447
|
get context() {
|
|
35285
|
-
if (!this._context) throw new Error("Step not prepared yet
|
|
35448
|
+
if (!this._context) throw new Error("Step not prepared yet \u2014 call prepare() first");
|
|
35286
35449
|
return this._context;
|
|
35287
35450
|
}
|
|
35288
35451
|
/**
|
|
@@ -35393,7 +35556,7 @@ var ObservationStep = class {
|
|
|
35393
35556
|
const inputIds = new Set(messageList.get.input.db().map((msg) => msg.id));
|
|
35394
35557
|
const sealedOutput = safeCandidates.filter((msg) => !inputIds.has(msg.id));
|
|
35395
35558
|
messageList.removeByIds(sealedOutput.map((msg) => msg.id));
|
|
35396
|
-
|
|
35559
|
+
if (sealedOutput.length) messageList.add(sealedOutput, "memory");
|
|
35397
35560
|
}
|
|
35398
35561
|
if (!deferred) {
|
|
35399
35562
|
om.trackBackgroundWork(om.buffer({
|
|
@@ -35442,7 +35605,7 @@ var ObservationStep = class {
|
|
|
35442
35605
|
}).map((msg) => msg.id);
|
|
35443
35606
|
inFlightIds = [...new Set(unreadIds)];
|
|
35444
35607
|
if (messagesToSave.length > 0) {
|
|
35445
|
-
|
|
35608
|
+
messageList.add(messagesToSave, "memory");
|
|
35446
35609
|
try {
|
|
35447
35610
|
await om.persistMessages(messagesToSave, threadId, resourceId);
|
|
35448
35611
|
} catch (error) {
|
|
@@ -35702,7 +35865,7 @@ var ObservationStep = class {
|
|
|
35702
35865
|
const messagesToSeal = messageToSeal ? [messageToSeal] : [];
|
|
35703
35866
|
this.turn.abortSignal?.throwIfAborted();
|
|
35704
35867
|
om.sealMessagesForBuffering(messagesToSeal);
|
|
35705
|
-
if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation
|
|
35868
|
+
if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation \u2014 step-0 seeded response message holds the active id");
|
|
35706
35869
|
else try {
|
|
35707
35870
|
await this.turn.hooks?.onSyncObservationComplete?.();
|
|
35708
35871
|
} catch (error) {
|
|
@@ -35853,12 +36016,12 @@ var ObservationTurn = class {
|
|
|
35853
36016
|
messageList;
|
|
35854
36017
|
/** The current cached record. Refreshed after mutations (activate/observe/reflect). */
|
|
35855
36018
|
get record() {
|
|
35856
|
-
if (!this._record) throw new Error("Turn not started
|
|
36019
|
+
if (!this._record) throw new Error("Turn not started \u2014 call start() first");
|
|
35857
36020
|
return this._record;
|
|
35858
36021
|
}
|
|
35859
36022
|
/** The context loaded during start(). */
|
|
35860
36023
|
get context() {
|
|
35861
|
-
if (!this._context) throw new Error("Turn not started
|
|
36024
|
+
if (!this._context) throw new Error("Turn not started \u2014 call start() first");
|
|
35862
36025
|
return this._context;
|
|
35863
36026
|
}
|
|
35864
36027
|
/** Whether the turn has been ended and can no longer accept steps. */
|
|
@@ -35927,7 +36090,7 @@ var ObservationTurn = class {
|
|
|
35927
36090
|
* (its output messages will be saved at the start of the new step's prepare()).
|
|
35928
36091
|
*/
|
|
35929
36092
|
step(stepNumber) {
|
|
35930
|
-
if (!this._started) throw new Error("Turn not started
|
|
36093
|
+
if (!this._started) throw new Error("Turn not started \u2014 call start() first");
|
|
35931
36094
|
if (this._ended) throw new Error("Turn already ended");
|
|
35932
36095
|
this._currentStep = new ObservationStep(this, stepNumber);
|
|
35933
36096
|
return this._currentStep;
|
|
@@ -35945,8 +36108,8 @@ var ObservationTurn = class {
|
|
|
35945
36108
|
this._ended = true;
|
|
35946
36109
|
const unsavedInput = messageList.get.input.db();
|
|
35947
36110
|
const unsavedOutput = messageList.get.response.db();
|
|
35948
|
-
const unsavedMessages = [...unsavedInput, ...unsavedOutput];
|
|
35949
|
-
if (unsavedMessages.length > 0) await this.om.persistMessages(unsavedMessages, this.threadId, this.resourceId);
|
|
36111
|
+
const unsavedMessages = withMessagesMarkedForResave(messageList, [...unsavedInput, ...unsavedOutput]);
|
|
36112
|
+
if (unsavedMessages.length > 0) await this.om.persistMessages(unsavedMessages, this.threadId, this.resourceId, idsMarkedForResave(messageList, [...unsavedInput, ...unsavedOutput]));
|
|
35950
36113
|
const asyncObservationEnabled = this.om.buffering.isAsyncObservationEnabled();
|
|
35951
36114
|
const bufferOnIdle = this.om.getObservationConfig().bufferOnIdle;
|
|
35952
36115
|
if (!this.abortSignal?.aborted && asyncObservationEnabled && bufferOnIdle) {
|
|
@@ -36150,8 +36313,8 @@ When consolidating observations:
|
|
|
36150
36313
|
- 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
|
|
36151
36314
|
- Prefer many short factual lines over prose summaries. Do not replace facts with generalities like "discussed travel plans"
|
|
36152
36315
|
- Combine related items where it makes sense (e.g., "agent called view tool 5 times on file x")
|
|
36153
|
-
- Preserve
|
|
36154
|
-
- Preserve the concrete resolved outcome captured by
|
|
36316
|
+
- Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
|
|
36317
|
+
- Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
|
|
36155
36318
|
- Condense the wording of older observations more than recent ones, but keep their facts
|
|
36156
36319
|
|
|
36157
36320
|
CRITICAL: USER ASSERTIONS vs QUESTIONS
|
|
@@ -36173,23 +36336,23 @@ When observations contain <thread id="..."> sections:
|
|
|
36173
36336
|
Example input:
|
|
36174
36337
|
<thread id="thread-1">
|
|
36175
36338
|
Date: Dec 4, 2025
|
|
36176
|
-
*
|
|
36177
|
-
*
|
|
36339
|
+
* \u{1F534} (14:30) User prefers TypeScript
|
|
36340
|
+
* \u{1F7E1} (14:35) Working on auth feature
|
|
36178
36341
|
</thread>
|
|
36179
36342
|
<thread id="thread-2">
|
|
36180
36343
|
Date: Dec 4, 2025
|
|
36181
|
-
*
|
|
36182
|
-
*
|
|
36344
|
+
* \u{1F534} (15:00) User prefers TypeScript
|
|
36345
|
+
* \u{1F7E1} (15:05) Debugging API endpoint
|
|
36183
36346
|
</thread>
|
|
36184
36347
|
|
|
36185
36348
|
Example output (consolidated):
|
|
36186
36349
|
Date: Dec 4, 2025
|
|
36187
|
-
*
|
|
36350
|
+
* \u{1F534} (14:30) User prefers TypeScript
|
|
36188
36351
|
<thread id="thread-1">
|
|
36189
|
-
*
|
|
36352
|
+
* \u{1F7E1} (14:35) Working on auth feature
|
|
36190
36353
|
</thread>
|
|
36191
36354
|
<thread id="thread-2">
|
|
36192
|
-
*
|
|
36355
|
+
* \u{1F7E1} (15:05) Debugging API endpoint
|
|
36193
36356
|
</thread>
|
|
36194
36357
|
|
|
36195
36358
|
=== OUTPUT FORMAT ===
|
|
@@ -36220,8 +36383,8 @@ Please re-process with slightly more compression:
|
|
|
36220
36383
|
- Memory is getting long - use a more condensed style throughout
|
|
36221
36384
|
- Combine related items more aggressively but do not lose important specific details of names, places, events, and people
|
|
36222
36385
|
- 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
|
|
36223
|
-
- Preserve
|
|
36224
|
-
- Preserve the concrete resolved outcome captured by
|
|
36386
|
+
- Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
|
|
36387
|
+
- Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
|
|
36225
36388
|
|
|
36226
36389
|
Aim for a 8/10 detail level.
|
|
36227
36390
|
`,
|
|
@@ -36237,8 +36400,8 @@ Please re-process with much more aggressive compression:
|
|
|
36237
36400
|
- Combine related items aggressively but do not lose important specific details of names, places, events, and people
|
|
36238
36401
|
- 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
|
|
36239
36402
|
- If the same file or module is mentioned across many observations, merge into one entry covering the full arc
|
|
36240
|
-
- Preserve
|
|
36241
|
-
- Preserve the concrete resolved outcome captured by
|
|
36403
|
+
- Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
|
|
36404
|
+
- Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
|
|
36242
36405
|
- Remove redundant information and merge overlapping observations
|
|
36243
36406
|
|
|
36244
36407
|
Aim for a 6/10 detail level.
|
|
@@ -36249,14 +36412,14 @@ Aim for a 6/10 detail level.
|
|
|
36249
36412
|
Your previous reflections have failed to compress sufficiently after multiple attempts.
|
|
36250
36413
|
|
|
36251
36414
|
Please re-process with maximum compression:
|
|
36252
|
-
- Summarize the oldest observations (first 50-70%) into brief high-level paragraphs
|
|
36415
|
+
- Summarize the oldest observations (first 50-70%) into brief high-level paragraphs \u2014 only key facts, decisions, and outcomes
|
|
36253
36416
|
- For the most recent observations (last 30-50%), retain important details but still use a condensed style
|
|
36254
|
-
- Ruthlessly merge related observations
|
|
36255
|
-
- Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries
|
|
36256
|
-
- Drop procedural details (tool calls, retries, intermediate steps)
|
|
36417
|
+
- Ruthlessly merge related observations \u2014 if 10 observations are about the same topic, combine into 1-2 lines
|
|
36418
|
+
- Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries \u2014 drop individual steps entirely
|
|
36419
|
+
- Drop procedural details (tool calls, retries, intermediate steps) \u2014 keep only final outcomes
|
|
36257
36420
|
- Drop observations that are no longer relevant or have been superseded by newer information
|
|
36258
|
-
- Preserve
|
|
36259
|
-
- Preserve the concrete resolved outcome captured by
|
|
36421
|
+
- Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
|
|
36422
|
+
- Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
|
|
36260
36423
|
- Preserve: names, dates, decisions, errors, user preferences, and architectural choices
|
|
36261
36424
|
|
|
36262
36425
|
Aim for a 4/10 detail level.
|
|
@@ -36267,14 +36430,14 @@ Aim for a 4/10 detail level.
|
|
|
36267
36430
|
Multiple compression attempts have failed. The content may already be dense from a prior reflection.
|
|
36268
36431
|
|
|
36269
36432
|
You MUST dramatically reduce the number of observations while keeping the standard observation format (date groups with bullet points and priority emojis):
|
|
36270
|
-
- Tool call observations are the biggest source of bloat. Collapse ALL tool call sequences into outcome-only observations
|
|
36271
|
-
- Never preserve individual tool calls (viewed file X, searched for Y, ran build)
|
|
36433
|
+
- 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")
|
|
36434
|
+
- Never preserve individual tool calls (viewed file X, searched for Y, ran build) \u2014 only preserve what was discovered or accomplished
|
|
36272
36435
|
- Consolidate many related observations into single, more generic observations
|
|
36273
36436
|
- Merge all same-day date groups into at most 2-3 date groups per day
|
|
36274
36437
|
- For older content, each topic or task should be at most 1-2 observations capturing the key outcome
|
|
36275
36438
|
- For recent content, retain more detail but still merge related items aggressively
|
|
36276
36439
|
- If multiple observations describe incremental progress on the same task, keep only the final state
|
|
36277
|
-
- Preserve
|
|
36440
|
+
- Preserve \u2705 completion markers and their outcomes but merge related completions into fewer lines
|
|
36278
36441
|
- Preserve: user preferences, key decisions, architectural choices, and unresolved issues
|
|
36279
36442
|
|
|
36280
36443
|
Aim for a 2/10 detail level. Fewer, more generic observations are better than many specific ones that exceed the budget.
|
|
@@ -36698,7 +36861,7 @@ var ReflectorRunner = class {
|
|
|
36698
36861
|
operationType: "reflection",
|
|
36699
36862
|
startedAt: streamContext.startedAt,
|
|
36700
36863
|
tokensAttempted: originalTokens,
|
|
36701
|
-
error: `Did not compress below threshold (${originalTokens}
|
|
36864
|
+
error: `Did not compress below threshold (${originalTokens} \u2192 ${reflectedTokens}, target: ${targetThreshold}), retrying at level ${currentLevel + 1}`,
|
|
36702
36865
|
retrying: true,
|
|
36703
36866
|
recordId: streamContext.recordId,
|
|
36704
36867
|
threadId: streamContext.threadId
|
|
@@ -36728,7 +36891,7 @@ var ReflectorRunner = class {
|
|
|
36728
36891
|
}
|
|
36729
36892
|
currentLevel = Math.min(currentLevel + 1, maxLevel);
|
|
36730
36893
|
}
|
|
36731
|
-
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)" : ""}
|
|
36894
|
+
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`);
|
|
36732
36895
|
const structuredExtraction = await extractStructuredValues({
|
|
36733
36896
|
agent,
|
|
36734
36897
|
source: "reflector",
|
|
@@ -36869,7 +37032,7 @@ var ReflectorRunner = class {
|
|
|
36869
37032
|
const reflectedObservationLineCount = linesToReflect;
|
|
36870
37033
|
const sliceTokenEstimate = Math.round(avgTokensPerLine * linesToReflect);
|
|
36871
37034
|
const compressionTarget = Math.round(sliceTokenEstimate * .75);
|
|
36872
|
-
omDebug(`[OM:reflect] doAsyncBufferedReflection: slicing observations for reflection
|
|
37035
|
+
omDebug(`[OM:reflect] doAsyncBufferedReflection: slicing observations for reflection \u2014 totalLines=${totalLines}, avgTokPerLine=${avgTokensPerLine.toFixed(1)}, activationPointTokens=${activationPointTokens}, linesToReflect=${linesToReflect}/${totalLines}, sliceTokenEstimate=${sliceTokenEstimate}, compressionTarget=${compressionTarget}`);
|
|
36873
37036
|
omDebug(`[OM:reflect] doAsyncBufferedReflection: starting reflector call, recordId=${currentRecord.id}, observationTokens=${sliceTokenEstimate}, compressionTarget=${compressionTarget} (inputTokens), activeObsLength=${activeObservations.length}, reflectedLineCount=${reflectedObservationLineCount}`);
|
|
36874
37037
|
if (writer) {
|
|
36875
37038
|
const startMarker = createBufferingStartMarker({
|
|
@@ -37041,7 +37204,7 @@ var ReflectorRunner = class {
|
|
|
37041
37204
|
const unreflectedTailTokens = unreflectedContent ? this.tokenCounter.countObservations(unreflectedContent) : 0;
|
|
37042
37205
|
const bufferedReflectionTokens = freshRecord.bufferedReflectionTokens ?? 0;
|
|
37043
37206
|
if (unreflectedTailTokens < bufferedReflectionTokens) {
|
|
37044
|
-
omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation
|
|
37207
|
+
omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation \u2014 unreflectedTailTokens=${unreflectedTailTokens} < bufferedReflectionTokens=${bufferedReflectionTokens}; keeping buffer for threshold activation`);
|
|
37045
37208
|
return {
|
|
37046
37209
|
status: "suppressed",
|
|
37047
37210
|
reason: "composition"
|
|
@@ -37052,7 +37215,7 @@ var ReflectorRunner = class {
|
|
|
37052
37215
|
const regularActivationTarget = reflectThreshold * (1 - bufferActivation);
|
|
37053
37216
|
const minCombinedTokens = Math.round(regularActivationTarget * EARLY_ACTIVATION_SIZE_FLOOR_RATIO);
|
|
37054
37217
|
if (combinedTokenCount < minCombinedTokens) {
|
|
37055
|
-
omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation
|
|
37218
|
+
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`);
|
|
37056
37219
|
return {
|
|
37057
37220
|
status: "suppressed",
|
|
37058
37221
|
reason: "size"
|
|
@@ -37181,7 +37344,7 @@ var ReflectorRunner = class {
|
|
|
37181
37344
|
omDebug(`[OM:reflect] isReflecting=true and active in this process, skipping`);
|
|
37182
37345
|
return;
|
|
37183
37346
|
}
|
|
37184
|
-
omDebug(`[OM:reflect] isReflecting=true but NOT active in this process
|
|
37347
|
+
omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
|
|
37185
37348
|
await this.storage.setReflectingFlag(record.id, false);
|
|
37186
37349
|
}
|
|
37187
37350
|
if (this.buffering.isAsyncReflectionEnabled()) {
|
|
@@ -37195,15 +37358,15 @@ var ReflectorRunner = class {
|
|
|
37195
37358
|
else {
|
|
37196
37359
|
const activationPoint = reflectThreshold * this.reflectionConfig.bufferActivation;
|
|
37197
37360
|
if (observationTokens < activationPoint) {
|
|
37198
|
-
omDebug(`[OM:reflect] skipping async reflection
|
|
37361
|
+
omDebug(`[OM:reflect] skipping async reflection \u2014 observationTokens (${observationTokens}) below activation point (${activationPoint}), triggered by ${activationTriggeredBy}`);
|
|
37199
37362
|
return;
|
|
37200
37363
|
}
|
|
37201
37364
|
const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
|
|
37202
37365
|
if (this.buffering.isAsyncBufferingInProgress(bufferKey) || BufferingCoordinator.lastBufferedBoundary.has(bufferKey)) {
|
|
37203
|
-
omDebug(`[OM:reflect] skipping async reflection
|
|
37366
|
+
omDebug(`[OM:reflect] skipping async reflection \u2014 reflection buffer already active or present for ${bufferKey}`);
|
|
37204
37367
|
return;
|
|
37205
37368
|
}
|
|
37206
|
-
omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter})
|
|
37369
|
+
omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) \u2014 starting background reflection`);
|
|
37207
37370
|
this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
|
|
37208
37371
|
return;
|
|
37209
37372
|
}
|
|
@@ -37211,7 +37374,7 @@ var ReflectorRunner = class {
|
|
|
37211
37374
|
if (activationTriggeredBy === "threshold") {
|
|
37212
37375
|
const suppressedAtTokens = this.syncReflectionSuppression.get(lockKey);
|
|
37213
37376
|
if (suppressedAtTokens !== void 0 && observationTokens === suppressedAtTokens) {
|
|
37214
|
-
omDebug(`[OM:reflect] skipping sync reflection
|
|
37377
|
+
omDebug(`[OM:reflect] skipping sync reflection \u2014 observations unchanged at ${observationTokens} tokens since the last unproductive attempt; retrying once they change`);
|
|
37215
37378
|
return;
|
|
37216
37379
|
}
|
|
37217
37380
|
}
|
|
@@ -38054,7 +38217,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
38054
38217
|
const asyncBufferingDisabled = config.observation?.bufferTokens === false || config.scope === "resource" && !userExplicitlyConfiguredAsync;
|
|
38055
38218
|
if (isSharedBudget && !asyncBufferingDisabled) {
|
|
38056
38219
|
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).");
|
|
38057
|
-
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
|
|
38220
|
+
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.");
|
|
38058
38221
|
}
|
|
38059
38222
|
const observationActivateAfterIdle = config.observation?.activateAfterIdle ?? config.activateAfterIdle;
|
|
38060
38223
|
const observationActivateAfterIdlePath = config.observation?.activateAfterIdle !== void 0 ? "observation.activateAfterIdle" : "activateAfterIdle";
|
|
@@ -38151,7 +38314,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
38151
38314
|
hasWarnedResourceScopeDeprecation = true;
|
|
38152
38315
|
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");
|
|
38153
38316
|
}
|
|
38154
|
-
omDebug(`[OM:init] new ObservationalMemory instance created
|
|
38317
|
+
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}`);
|
|
38155
38318
|
}
|
|
38156
38319
|
__registerMastra(mastra) {
|
|
38157
38320
|
this.mastra = mastra;
|
|
@@ -38432,7 +38595,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
38432
38595
|
threadId: null,
|
|
38433
38596
|
resourceId: resourceId ?? threadId
|
|
38434
38597
|
};
|
|
38435
|
-
if (!threadId) throw new Error("ObservationalMemory (scope: 'thread') requires a threadId, but received an empty value. This is a bug
|
|
38598
|
+
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.");
|
|
38436
38599
|
return {
|
|
38437
38600
|
threadId,
|
|
38438
38601
|
resourceId: resourceId ?? threadId
|
|
@@ -38743,7 +38906,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
38743
38906
|
const isImportant = new Array(totalCount);
|
|
38744
38907
|
for (let i = 0; i < totalCount; i++) {
|
|
38745
38908
|
lineTokens[i] = this.tokenCounter.countString(lines[i]);
|
|
38746
|
-
isImportant[i] = lines[i].includes("
|
|
38909
|
+
isImportant[i] = lines[i].includes("\u{1F534}") || lines[i].includes("\u2705");
|
|
38747
38910
|
}
|
|
38748
38911
|
const suffixTokens = new Array(totalCount + 1);
|
|
38749
38912
|
suffixTokens[totalCount] = 0;
|
|
@@ -38855,18 +39018,86 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
38855
39018
|
* to detect already-persisted messages, avoiding redundant DB operations.
|
|
38856
39019
|
*
|
|
38857
39020
|
* Messages with observation markers are always saved (upserted) even if sealed,
|
|
38858
|
-
* because the markers need to be persisted to storage.
|
|
39021
|
+
* because the markers need to be persisted to storage. A stored message in `resaveIds` gained token
|
|
39022
|
+
* counts after it was stored, whether or not it is sealed: only those counts are copied onto the stored
|
|
39023
|
+
* copy, see {@link persistTokenEstimatesOntoStored}; one with no stored row was deleted during the turn and stays deleted. Ids in `resaveIds` must not be this turn's own
|
|
39024
|
+
* input or output, which are saved whole.
|
|
38859
39025
|
*/
|
|
38860
|
-
async persistMessages(messagesToSave, threadId, resourceId) {
|
|
39026
|
+
async persistMessages(messagesToSave, threadId, resourceId, resaveIds) {
|
|
38861
39027
|
const filteredMessages = [];
|
|
38862
|
-
|
|
38863
|
-
|
|
38864
|
-
|
|
39028
|
+
const storedWithNewCounts = [];
|
|
39029
|
+
for (const msg of messagesToSave) {
|
|
39030
|
+
if (!!(msg.content?.metadata)?.mastra?.sealed && findLastCompletedObservationBoundary(msg) === -1 && !resaveIds?.has(msg.id)) continue;
|
|
39031
|
+
if (resaveIds?.has(msg.id) && findLastCompletedObservationBoundary(msg) === -1) storedWithNewCounts.push(msg);
|
|
39032
|
+
else filteredMessages.push(msg);
|
|
39033
|
+
}
|
|
38865
39034
|
if (filteredMessages.length > 0) await this.messageHistory.persistMessages({
|
|
38866
39035
|
messages: filteredMessages,
|
|
38867
39036
|
threadId,
|
|
38868
39037
|
resourceId
|
|
38869
39038
|
});
|
|
39039
|
+
try {
|
|
39040
|
+
await this.persistTokenEstimatesOntoStored(storedWithNewCounts);
|
|
39041
|
+
} catch (error) {
|
|
39042
|
+
omError("[OM] Failed to save token counts for stored messages", error);
|
|
39043
|
+
}
|
|
39044
|
+
}
|
|
39045
|
+
/**
|
|
39046
|
+
* Copy the token counts of `messages` onto their stored copies. A stored copy can hold
|
|
39047
|
+
* parts the in-memory one lacks (markers written straight to storage), so it is patched
|
|
39048
|
+
* instead of saved whole. Each count goes to the first stored part whose content matches the counted
|
|
39049
|
+
* part, so a part that changed in storage keeps no count and is counted again on read.
|
|
39050
|
+
*/
|
|
39051
|
+
async persistTokenEstimatesOntoStored(messages) {
|
|
39052
|
+
if (messages.length === 0) return;
|
|
39053
|
+
const contentOf = (part) => {
|
|
39054
|
+
const { tokenEstimate: _tokenEstimate, ...mastra } = part.providerMetadata?.mastra ?? {};
|
|
39055
|
+
return JSON.stringify({
|
|
39056
|
+
...part,
|
|
39057
|
+
providerMetadata: {
|
|
39058
|
+
...part.providerMetadata,
|
|
39059
|
+
mastra
|
|
39060
|
+
}
|
|
39061
|
+
});
|
|
39062
|
+
};
|
|
39063
|
+
const live = new Map(messages.map((message) => [message.id, message]));
|
|
39064
|
+
const { messages: stored } = await this.storage.listMessagesById({ messageIds: [...live.keys()] });
|
|
39065
|
+
const updates = [];
|
|
39066
|
+
for (const row of stored) {
|
|
39067
|
+
const counts = /* @__PURE__ */ new Map();
|
|
39068
|
+
for (const part of live.get(row.id)?.content.parts ?? []) {
|
|
39069
|
+
const tokenEstimate = part.providerMetadata?.mastra?.tokenEstimate;
|
|
39070
|
+
if (!tokenEstimate) continue;
|
|
39071
|
+
const key = contentOf(part);
|
|
39072
|
+
counts.set(key, [...counts.get(key) ?? [], tokenEstimate]);
|
|
39073
|
+
}
|
|
39074
|
+
if (counts.size === 0) continue;
|
|
39075
|
+
let changed = false;
|
|
39076
|
+
const parts = row.content.parts.map((part) => {
|
|
39077
|
+
const tokenEstimate = counts.get(contentOf(part))?.shift();
|
|
39078
|
+
if (!tokenEstimate) return part;
|
|
39079
|
+
changed = true;
|
|
39080
|
+
const providerMetadata = part.providerMetadata ?? {};
|
|
39081
|
+
return {
|
|
39082
|
+
...part,
|
|
39083
|
+
providerMetadata: {
|
|
39084
|
+
...providerMetadata,
|
|
39085
|
+
mastra: {
|
|
39086
|
+
...providerMetadata.mastra,
|
|
39087
|
+
tokenEstimate
|
|
39088
|
+
}
|
|
39089
|
+
}
|
|
39090
|
+
};
|
|
39091
|
+
});
|
|
39092
|
+
if (changed) updates.push({
|
|
39093
|
+
id: row.id,
|
|
39094
|
+
content: {
|
|
39095
|
+
...row.content,
|
|
39096
|
+
parts
|
|
39097
|
+
}
|
|
39098
|
+
});
|
|
39099
|
+
}
|
|
39100
|
+
if (updates.length > 0) await this.storage.updateMessages({ messages: updates });
|
|
38870
39101
|
}
|
|
38871
39102
|
/**
|
|
38872
39103
|
* Load messages from storage that haven't been observed yet.
|
|
@@ -39076,7 +39307,7 @@ ${formattedMessages}
|
|
|
39076
39307
|
resourceId: freshRecord.resourceId ?? void 0
|
|
39077
39308
|
});
|
|
39078
39309
|
} catch (err) {
|
|
39079
|
-
omError("[OM] Failed to persist sealed messages before buffering
|
|
39310
|
+
omError("[OM] Failed to persist sealed messages before buffering \u2014 skipping observation cycle", err);
|
|
39080
39311
|
return;
|
|
39081
39312
|
}
|
|
39082
39313
|
const cycleId = `buffer-obs-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
|
|
@@ -40226,7 +40457,7 @@ ${formattedMessages}
|
|
|
40226
40457
|
usage: void 0
|
|
40227
40458
|
};
|
|
40228
40459
|
}
|
|
40229
|
-
omDebug(`[OM:reflect] isReflecting=true but NOT active in this process
|
|
40460
|
+
omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
|
|
40230
40461
|
await this.storage.setReflectingFlag(record.id, false);
|
|
40231
40462
|
}
|
|
40232
40463
|
await this.storage.setReflectingFlag(record.id, true);
|
|
@@ -40461,7 +40692,7 @@ ${formattedMessages}
|
|
|
40461
40692
|
// src/processors/observational-memory/temporal-markers.ts
|
|
40462
40693
|
const TEMPORAL_GAP_REMINDER_TYPE = "temporal-gap";
|
|
40463
40694
|
function getTemporalGapReminderText(gapText, timestamp) {
|
|
40464
|
-
return `${gapText}
|
|
40695
|
+
return `${gapText} \u2014 ${formatTemporalTimestamp(new Date(timestamp))}`;
|
|
40465
40696
|
}
|
|
40466
40697
|
function getTemporalGapReminderMetadata(message, gapText, gapMs, timestamp) {
|
|
40467
40698
|
const formattedTimestamp = formatTemporalTimestamp(new Date(timestamp));
|
|
@@ -40669,11 +40900,12 @@ var ObservationalMemoryProcessor = class {
|
|
|
40669
40900
|
state.__omTurn = void 0;
|
|
40670
40901
|
if (!activeTurn || activeTurn.ended) return;
|
|
40671
40902
|
const terminalList = messageList ?? activeTurn.messageList;
|
|
40672
|
-
const
|
|
40903
|
+
const ownMessages = [...terminalList.get.input.db(), ...terminalList.get.response.db()];
|
|
40904
|
+
const unsavedMessages = withMessagesMarkedForResave(terminalList, ownMessages);
|
|
40673
40905
|
try {
|
|
40674
40906
|
await activeTurn.end(terminalList);
|
|
40675
40907
|
} catch (error) {
|
|
40676
|
-
if (unsavedMessages.length > 0) await this.engine.persistMessages(unsavedMessages, activeTurn.threadId, activeTurn.resourceId).catch(() => {});
|
|
40908
|
+
if (unsavedMessages.length > 0) await this.engine.persistMessages(unsavedMessages, activeTurn.threadId, activeTurn.resourceId, idsMarkedForResave(terminalList, ownMessages)).catch(() => {});
|
|
40677
40909
|
throw error;
|
|
40678
40910
|
}
|
|
40679
40911
|
}
|
|
@@ -40683,14 +40915,14 @@ var ObservationalMemoryProcessor = class {
|
|
|
40683
40915
|
omDebug(`[OM:processInputStep:ENTER] step=${stepNumber}, hasMastraMemory=${!!requestContext?.get("MastraMemory")}, hasMemoryInfo=${!!messageList?.serialize()?.memoryInfo?.threadId}`);
|
|
40684
40916
|
const context = this.engine.getThreadContext(requestContext, messageList);
|
|
40685
40917
|
if (!context) {
|
|
40686
|
-
omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null
|
|
40918
|
+
omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null \u2014 returning early`);
|
|
40687
40919
|
return messageList;
|
|
40688
40920
|
}
|
|
40689
40921
|
const gatewayMemoryManaged = await isGatewayMemoryManaged(model);
|
|
40690
40922
|
state[GATEWAY_STATE_KEY] = gatewayMemoryManaged;
|
|
40691
40923
|
if (gatewayMemoryManaged) {
|
|
40692
40924
|
await this.endActiveTurn(state);
|
|
40693
|
-
omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory
|
|
40925
|
+
omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory \u2014 skipping local processing`);
|
|
40694
40926
|
return messageList;
|
|
40695
40927
|
}
|
|
40696
40928
|
const { threadId, resourceId } = context;
|
|
@@ -40815,6 +41047,7 @@ var ObservationalMemoryProcessor = class {
|
|
|
40815
41047
|
this.turn.responseMessageId = responseMessageId;
|
|
40816
41048
|
{
|
|
40817
41049
|
const step = this.turn.step(stepNumber);
|
|
41050
|
+
const resaveCounted = resaveCountedMessagesFor(messageList, threadId);
|
|
40818
41051
|
let ctx;
|
|
40819
41052
|
try {
|
|
40820
41053
|
ctx = await step.prepare();
|
|
@@ -40849,6 +41082,7 @@ var ObservationalMemoryProcessor = class {
|
|
|
40849
41082
|
threadId,
|
|
40850
41083
|
resourceId
|
|
40851
41084
|
});
|
|
41085
|
+
resaveCounted();
|
|
40852
41086
|
const finalTotalPending = ctx.status.pendingTokens;
|
|
40853
41087
|
try {
|
|
40854
41088
|
await runOMCommit(this.engine.buffering.getLockKey(threadId, resourceId), () => this.engine.getStorage().setPendingMessageTokens(turnRecord.id, finalTotalPending), { abortSignal });
|
|
@@ -40888,6 +41122,7 @@ var ObservationalMemoryProcessor = class {
|
|
|
40888
41122
|
return this.engine.getTokenCounter().runWithModelContext(state.__omActorModelContext, async () => {
|
|
40889
41123
|
if (parseMemoryRequestContext(requestContext)?.memoryConfig?.readOnly) return messageList;
|
|
40890
41124
|
const persistenceMessageList = messageList.cloneForPersistence();
|
|
41125
|
+
this.engine.getTokenCounter().countMessages(persistenceMessageList.get.response.db());
|
|
40891
41126
|
const turn = asLiveTurn(state.__omTurn) ?? this.turn;
|
|
40892
41127
|
const liveTurn = turn && !turn.ended ? turn : void 0;
|
|
40893
41128
|
if (liveTurn) await liveTurn.end(persistenceMessageList);
|
|
@@ -40895,8 +41130,9 @@ var ObservationalMemoryProcessor = class {
|
|
|
40895
41130
|
state.__omTurn = void 0;
|
|
40896
41131
|
if (!liveTurn) {
|
|
40897
41132
|
const newOutput = persistenceMessageList.get.response.db();
|
|
40898
|
-
const
|
|
40899
|
-
|
|
41133
|
+
const ownMessages = [...persistenceMessageList.get.input.db(), ...newOutput];
|
|
41134
|
+
const messagesToSave = withMessagesMarkedForResave(persistenceMessageList, ownMessages);
|
|
41135
|
+
if (messagesToSave.length > 0 && context.threadId) await this.engine.persistMessages(messagesToSave, context.threadId, context.resourceId, idsMarkedForResave(persistenceMessageList, ownMessages));
|
|
40900
41136
|
}
|
|
40901
41137
|
return messageList;
|
|
40902
41138
|
});
|
|
@@ -40911,7 +41147,7 @@ var ObservationalMemoryProcessor = class {
|
|
|
40911
41147
|
if (!context) return;
|
|
40912
41148
|
if (parseMemoryRequestContext(requestContext)?.memoryConfig?.readOnly) return;
|
|
40913
41149
|
state[CONTEXT_OVERFLOW_STEP_KEY] = stepNumber;
|
|
40914
|
-
omDebug(`[OM:processAPIError] context overflow at step ${stepNumber}
|
|
41150
|
+
omDebug(`[OM:processAPIError] context overflow at step ${stepNumber} \u2014 observing pending messages`);
|
|
40915
41151
|
const { threadId, resourceId } = context;
|
|
40916
41152
|
await this.engine.waitForBuffering(threadId, resourceId, void 0, args.abortSignal);
|
|
40917
41153
|
const messages = getObservableMessages(messageList);
|