@mastra/memory 1.41.3-alpha.3 → 1.41.3-alpha.4
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/integrations-databases-libsql.md +1 -1
- 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/{src-CDIIMmAU.cjs → src-CKIbQdMJ.cjs} +143 -132
- package/dist/{src-CDv__4kY.js → src-TRQ73bGO.js} +143 -132
- package/package.json +5 -5
|
@@ -24283,14 +24283,14 @@ function getRetrievalInstructions(scope = "resource", customInstructions, search
|
|
|
24283
24283
|
The recall tool works across ALL of this user's conversation threads, not just the current one.
|
|
24284
24284
|
|
|
24285
24285
|
- Use \`mode: "search"\` with a \`query\` to find relevant history, even when you already know the thread. Each result includes its thread ID, observation group ID, and source message range.
|
|
24286
|
-
- Use \`mode: "messages"\` for original wording or details behind an observation
|
|
24286
|
+
- Use \`mode: "messages"\` for original wording or details behind an observation \u2014 pass \`threadId\` to read another thread and a \`cursor\` from the source message range.
|
|
24287
24287
|
- Use \`mode: "threads"\` to list the user's threads (IDs, titles, dates) when you need to discover where something was discussed. Use \`before\`/\`after\` to narrow by date.
|
|
24288
24288
|
|
|
24289
|
-
**If search results look irrelevant, do not give up.** Search only covers content that has been indexed
|
|
24289
|
+
**If search results look irrelevant, do not give up.** Search only covers content that has been indexed \u2014 a short or recent conversation may exist in raw message history before any observation of it was created. When search returns nothing suitable but the user is clearly referring to a past conversation, call \`mode: "threads"\` to find candidate threads (titles and dates are strong clues), then read them with \`mode: "messages"\`. Use a useful hit as an entry point to the surrounding history rather than treating it as the whole answer.` : `### Choosing a mode
|
|
24290
24290
|
The recall tool works across ALL of this user's conversation threads, not just the current one.
|
|
24291
24291
|
|
|
24292
24292
|
- Use \`mode: "threads"\` to list the user's threads (IDs, titles, dates) when you need to discover where something was discussed. Use \`before\`/\`after\` to narrow by date.
|
|
24293
|
-
- Use \`mode: "messages"\` when you know the thread
|
|
24293
|
+
- Use \`mode: "messages"\` when you know the thread \u2014 pass \`threadId\` to read another thread, or a \`cursor\` from an observation-group range.
|
|
24294
24294
|
|
|
24295
24295
|
When the user refers to a past conversation you don't have a cursor for, call \`mode: "threads"\` to find candidate threads (titles and dates are strong clues), then read them with \`mode: "messages"\`. Raw history may exist for threads that have no observations yet.` : `### Choosing a mode
|
|
24296
24296
|
The recall tool is limited to the current conversation thread.
|
|
@@ -24315,7 +24315,7 @@ When searches keep returning the same groups, often as already-in-context refere
|
|
|
24315
24315
|
"Excerpt already in current context" marks a hit whose text an earlier search result already shows. "Group already in current context" marks a group that is already in your observations or whose source messages are still in the conversation. "Source range overlaps current context" marks a group whose source messages are still in the conversation. Search keeps these references and tries lower-ranked matches to fill the requested number of excerpts. This backfill is bounded: fewer excerpts do not mean history is exhausted. Use the evidence already present rather than repeating the same lookup. You can still ${pagingEnabled ? "page a referenced group" : "read a referenced group's source messages"} when you need all of it, or search again if that context is no longer available.
|
|
24316
24316
|
|
|
24317
24317
|
If search still finds nothing useful, browse raw messages${isResource ? " or discover other threads" : " in this thread"} before concluding the information is unavailable. Raw history may exist for threads that have no observations yet.` : "";
|
|
24318
|
-
const base = `## Recall
|
|
24318
|
+
const base = `## Recall \u2014 looking up source messages
|
|
24319
24319
|
|
|
24320
24320
|
Your memory contains observation groups with IDs and source message ranges, shown as \`## Group\` headings with \`_range: startId:endId\` or as \`<observation-group>\` tags. Use the **recall** tool to recover retained original observations and source messages.
|
|
24321
24321
|
|
|
@@ -24326,13 +24326,13 @@ Groups marked \`kind="reflection"\` (rendered as \`_kind: reflection_\`) are los
|
|
|
24326
24326
|
|
|
24327
24327
|
### When to use recall
|
|
24328
24328
|
- The user asks you to **repeat, show, or reproduce** something from a past conversation
|
|
24329
|
-
- The user asks for **exact content**
|
|
24329
|
+
- The user asks for **exact content** \u2014 code, text, quotes, error messages, URLs, file paths, specific numbers
|
|
24330
24330
|
- Your observations mention something but your memory lacks the detail needed to fully answer (e.g. you know a blog post was shared but only have a summary of it)
|
|
24331
24331
|
- You want to **verify or expand on** an observation before responding
|
|
24332
24332
|
- The answer depends on historical dates, order, or duration: verify both event dates and that they refer to the events the user means. Distinguish a plan, an actual start, a later update, and a repeated mention instead of choosing a nearby date from a summary
|
|
24333
24333
|
- An observation records something the assistant proposed, such as a schedule, date, or plan, and your observations don't show what the user decided. Read the raw messages around it to find the user's decision before treating the proposal as what happened
|
|
24334
24334
|
- Relevant details are missing, ambiguous, or conflicting in the current observations${isResource ? `
|
|
24335
|
-
- The user references another conversation that your observations don't cover
|
|
24335
|
+
- The user references another conversation that your observations don't cover \u2014 even if you have no observations yet, their other threads may contain it` : ""}
|
|
24336
24336
|
|
|
24337
24337
|
**Default to using recall when the user references specific past content.** Your observations capture the gist, not the details. If there's any doubt whether your memory is complete enough, use recall.
|
|
24338
24338
|
|
|
@@ -24367,17 +24367,17 @@ Each range has the format \`startId:endId\` where both are message IDs separated
|
|
|
24367
24367
|
In \`mode: "messages"\`, recall returns **low** detail by default: truncated text and tool names only. Each message shows its ID and each part has a positional index like \`[p0]\`, \`[p1]\`, etc.
|
|
24368
24368
|
|
|
24369
24369
|
- Use \`detail: "high"\` to get full message content including tool arguments and results. This will only return the high detail version of a single message part at a time.
|
|
24370
|
-
- Use \`partIndex\` with a cursor to fetch a single part at full detail
|
|
24370
|
+
- Use \`partIndex\` with a cursor to fetch a single part at full detail \u2014 for example, to read one specific tool result or code block without loading every part.
|
|
24371
24371
|
|
|
24372
24372
|
If the result says \`truncated: true\`, the output was cut to fit the token budget. You can paginate or use \`partIndex\` to target specific content. If a single part is itself too large, follow the returned \`nextCharOffset\` as described below.
|
|
24373
24373
|
|
|
24374
24374
|
### Following up on truncated parts
|
|
24375
24375
|
Low-detail results may include truncation hints like:
|
|
24376
|
-
\`[truncated
|
|
24376
|
+
\`[truncated \u2014 call recall cursor="..." partIndex=N detail="high" for full content]\`
|
|
24377
24377
|
|
|
24378
24378
|
**When you see these hints and need the full content, make the exact call described in the hint.** This is the normal workflow: first recall at low detail to scan, then drill into specific parts at high detail. Do not stop at the low-detail result if the user asked for exact content.
|
|
24379
24379
|
|
|
24380
|
-
If a single part is larger than the token budget, the \`partIndex\` result is \`truncated: true\` and includes \`nextCharOffset\`. Repeat the same call with \`charOffset\` set to that exact value to read the next chunk from where the previous one ended. Keep following \`nextCharOffset\` until the result no longer includes it
|
|
24380
|
+
If a single part is larger than the token budget, the \`partIndex\` result is \`truncated: true\` and includes \`nextCharOffset\`. Repeat the same call with \`charOffset\` set to that exact value to read the next chunk from where the previous one ended. Keep following \`nextCharOffset\` until the result no longer includes it \u2014 the chunks together contain the full part. Retrying without \`charOffset\` returns the same prefix again.
|
|
24381
24381
|
|
|
24382
24382
|
### When recall is NOT needed
|
|
24383
24383
|
- The user is asking for a high-level summary and your observations already cover it
|
|
@@ -24774,6 +24774,15 @@ function buildThreadMetadataFromExtractedValues(extractors, values) {
|
|
|
24774
24774
|
async function applyExtractorHooks(opts) {
|
|
24775
24775
|
const values = normalizeExtractedValues(opts.values) ?? {};
|
|
24776
24776
|
const failures = [...opts.failures ?? []];
|
|
24777
|
+
let recentMessages;
|
|
24778
|
+
let recentMessagesResolved = false;
|
|
24779
|
+
const resolveRecentMessages = () => {
|
|
24780
|
+
if (!recentMessagesResolved) {
|
|
24781
|
+
recentMessages = typeof opts.recentMessages === "function" ? opts.recentMessages() : opts.recentMessages;
|
|
24782
|
+
recentMessagesResolved = true;
|
|
24783
|
+
}
|
|
24784
|
+
return recentMessages;
|
|
24785
|
+
};
|
|
24777
24786
|
for (const extractor of opts.extractors) {
|
|
24778
24787
|
const isHook = extractor.mode === "hook";
|
|
24779
24788
|
const hasValue = Object.prototype.hasOwnProperty.call(values, extractor.slug);
|
|
@@ -24793,7 +24802,9 @@ async function applyExtractorHooks(opts) {
|
|
|
24793
24802
|
previous: isHook ? void 0 : opts.previousValues?.[extractor.slug],
|
|
24794
24803
|
current,
|
|
24795
24804
|
rawObservations: opts.rawObservations,
|
|
24796
|
-
recentMessages
|
|
24805
|
+
get recentMessages() {
|
|
24806
|
+
return resolveRecentMessages();
|
|
24807
|
+
},
|
|
24797
24808
|
mainAgent: opts.mainAgent,
|
|
24798
24809
|
memory: opts.memory,
|
|
24799
24810
|
sendSignal: opts.sendSignal,
|
|
@@ -25552,7 +25563,7 @@ const YEAR = String.raw`(?:19|20|21)\d{2}(?!\d)`;
|
|
|
25552
25563
|
const MERIDIEM = String.raw`(?:[AaPp]\.[Mm]\.|[AaPp][Mm]\b)`;
|
|
25553
25564
|
const TIME = String.raw`(?:,?\s+(?:at\s+)?\d{1,2}:\d{2}(?:\s*${MERIDIEM})?|\s+at\s+\d{1,2}\s*${MERIDIEM})`;
|
|
25554
25565
|
const QUALIFIER = String.raw`(?:(?:early|mid|late)[- ](?:to[- ](?:early|mid|late)[- ])?)`;
|
|
25555
|
-
const RANGE_SEP = String.raw`(?:\s*[
|
|
25566
|
+
const RANGE_SEP = String.raw`(?:\s*[\u2013\u2014]\s*|\s*-\s*|\s+(?:to|through|until)\s+)`;
|
|
25556
25567
|
/**
|
|
25557
25568
|
* Dates written into observation text that carry their own year, longest forms first:
|
|
25558
25569
|
* "Mar 1 - Mar 18, 2025", "May 27-28, 2023", "January 10, 2024 at 3:00 PM",
|
|
@@ -25855,15 +25866,15 @@ const SHORT_TOKEN_THRESHOLD = 3;
|
|
|
25855
25866
|
const KANA_CHARS_PER_TOKEN = 1.35;
|
|
25856
25867
|
const DEFAULT_LANGUAGE_CONFIGS = [
|
|
25857
25868
|
{
|
|
25858
|
-
pattern: /[
|
|
25869
|
+
pattern: /[\u00E4\u00F6\u00FC\u00DF\u1E9E]/i,
|
|
25859
25870
|
averageCharsPerToken: 2.6
|
|
25860
25871
|
},
|
|
25861
25872
|
{
|
|
25862
|
-
pattern: /[
|
|
25873
|
+
pattern: /[\u00E9\u00E8\u00EA\u00EB\u00E0\u00E2\u00EE\u00EF\u00F4\u00FB\u00F9\u00FC\u00FF\u00E7\u0153\u00E6\u00E1\u00ED\u00F3\u00FA\u00F1]/i,
|
|
25863
25874
|
averageCharsPerToken: 3
|
|
25864
25875
|
},
|
|
25865
25876
|
{
|
|
25866
|
-
pattern: /[
|
|
25877
|
+
pattern: /[\u0105\u0107\u0119\u0142\u0144\u00F3\u015B\u017A\u017C\u011B\u0161\u010D\u0159\u017E\u00FD\u016F\u00FA\u010F\u0165\u0148]/i,
|
|
25867
25878
|
averageCharsPerToken: 2.5
|
|
25868
25879
|
},
|
|
25869
25880
|
{
|
|
@@ -25952,10 +25963,10 @@ function sanitizeSurrogates(value) {
|
|
|
25952
25963
|
if (next >= 56320 && next <= 57343) {
|
|
25953
25964
|
sanitized += value.charAt(index) + value.charAt(index + 1);
|
|
25954
25965
|
index++;
|
|
25955
|
-
} else sanitized += "
|
|
25966
|
+
} else sanitized += "\uFFFD";
|
|
25956
25967
|
continue;
|
|
25957
25968
|
}
|
|
25958
|
-
sanitized += code >= 56320 && code <= 57343 ? "
|
|
25969
|
+
sanitized += code >= 56320 && code <= 57343 ? "\uFFFD" : value[index];
|
|
25959
25970
|
}
|
|
25960
25971
|
return sanitized;
|
|
25961
25972
|
}
|
|
@@ -25977,7 +25988,7 @@ function truncatePath(path) {
|
|
|
25977
25988
|
const headLength = 50;
|
|
25978
25989
|
const tailLength = 60;
|
|
25979
25990
|
const omitted = path.length - headLength - tailLength;
|
|
25980
|
-
return `${safeSlice(path, headLength)}
|
|
25991
|
+
return `${safeSlice(path, headLength)}\u2026[${omitted} chars; ${stablePathDigest(path)}]\u2026${safeTail(path, tailLength)}`;
|
|
25981
25992
|
}
|
|
25982
25993
|
function formatPath(parent, key, isArray) {
|
|
25983
25994
|
if (isArray) return truncatePath(`${parent}[${key}]`);
|
|
@@ -26086,7 +26097,7 @@ function selectOutlineEntries(entries, limits) {
|
|
|
26086
26097
|
const rendered = joinEntries(selected, marker);
|
|
26087
26098
|
if (fits(rendered, limits)) return rendered;
|
|
26088
26099
|
if (fits(marker, limits)) return marker;
|
|
26089
|
-
return fits("
|
|
26100
|
+
return fits("\u2026", limits) ? "\u2026" : "";
|
|
26090
26101
|
}
|
|
26091
26102
|
function indentPreview(value) {
|
|
26092
26103
|
return value.split("\n").map((line) => ` | ${line}`).join("\n");
|
|
@@ -26129,13 +26140,13 @@ function formatToolArgumentsForObserver(value, options) {
|
|
|
26129
26140
|
if (!isObjectLike$1(value)) {
|
|
26130
26141
|
if (typeof value !== "string" || value.length <= OBSERVER_TOOL_ARGUMENT_INLINE_STRING_MAX_CHARS) {
|
|
26131
26142
|
const primitive = formatPrimitive(value);
|
|
26132
|
-
return fits(primitive, limits) ? primitive : fits("
|
|
26143
|
+
return fits(primitive, limits) ? primitive : fits("\u2026", limits) ? "\u2026" : "";
|
|
26133
26144
|
}
|
|
26134
26145
|
const summary = `<string, ${value.length} characters; preview size-limited>`;
|
|
26135
26146
|
const rendered = appendWithinBudget(summary, formatPreview("preview", value, limits, summary), limits);
|
|
26136
26147
|
if (rendered) return rendered;
|
|
26137
26148
|
if (fits(summary, limits)) return summary;
|
|
26138
|
-
return fits("
|
|
26149
|
+
return fits("\u2026", limits) ? "\u2026" : "";
|
|
26139
26150
|
}
|
|
26140
26151
|
const outline = [];
|
|
26141
26152
|
const previews = [];
|
|
@@ -26381,24 +26392,24 @@ function formatToolResultForObserver(value, options) {
|
|
|
26381
26392
|
const OBSERVER_EXTRACTION_INSTRUCTIONS = `CRITICAL: DISTINGUISH USER ASSERTIONS FROM QUESTIONS
|
|
26382
26393
|
|
|
26383
26394
|
When the user TELLS you something about themselves, mark it as an assertion:
|
|
26384
|
-
- "I have two kids"
|
|
26385
|
-
- "I work at Acme Corp"
|
|
26386
|
-
- "I graduated in 2019"
|
|
26395
|
+
- "I have two kids" \u2192 \u{1F534} (14:30) User stated has two kids
|
|
26396
|
+
- "I work at Acme Corp" \u2192 \u{1F534} (14:31) User stated works at Acme Corp
|
|
26397
|
+
- "I graduated in 2019" \u2192 \u{1F534} (14:32) User stated graduated in 2019
|
|
26387
26398
|
|
|
26388
26399
|
When the user ASKS about something, mark it as a question/request:
|
|
26389
|
-
- "Can you help me with X?"
|
|
26390
|
-
- "What's the best way to do Y?"
|
|
26400
|
+
- "Can you help me with X?" \u2192 \u{1F534} (15:00) User asked help with X
|
|
26401
|
+
- "What's the best way to do Y?" \u2192 \u{1F534} (15:01) User asked best way to do Y
|
|
26391
26402
|
|
|
26392
26403
|
Distinguish between QUESTIONS and STATEMENTS OF INTENT:
|
|
26393
|
-
- "Can you recommend..."
|
|
26394
|
-
- "I'm looking forward to [doing X]"
|
|
26395
|
-
- "I need to [do X]"
|
|
26404
|
+
- "Can you recommend..." \u2192 Question (extract as "User asked...")
|
|
26405
|
+
- "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)")
|
|
26406
|
+
- "I need to [do X]" \u2192 Statement of intent (extract as "User stated they need to [do X] (again, add date if mentioned)")
|
|
26396
26407
|
|
|
26397
26408
|
STATE CHANGES AND UPDATES:
|
|
26398
26409
|
When a user indicates they are changing something, frame it as a state change that supersedes previous information:
|
|
26399
|
-
- "I'm going to start doing X instead of Y"
|
|
26400
|
-
- "I'm switching from A to B"
|
|
26401
|
-
- "I moved my stuff to the new place"
|
|
26410
|
+
- "I'm going to start doing X instead of Y" \u2192 "User will start doing X (changing from Y)"
|
|
26411
|
+
- "I'm switching from A to B" \u2192 "User is switching from A to B"
|
|
26412
|
+
- "I moved my stuff to the new place" \u2192 "User moved their stuff to the new place (no longer at previous location)"
|
|
26402
26413
|
|
|
26403
26414
|
If the new state contradicts or updates previous information, make that explicit:
|
|
26404
26415
|
- BAD: "User plans to use the new method"
|
|
@@ -26489,11 +26500,11 @@ BAD: User got something.
|
|
|
26489
26500
|
GOOD: User purchased / received / was given something. (be specific)
|
|
26490
26501
|
|
|
26491
26502
|
Common clarifications:
|
|
26492
|
-
- "getting" something regularly
|
|
26493
|
-
- "getting" something once
|
|
26494
|
-
- "got"
|
|
26495
|
-
- "signed up"
|
|
26496
|
-
- "stopped getting"
|
|
26503
|
+
- "getting" something regularly \u2192 "subscribed to" or "enrolled in"
|
|
26504
|
+
- "getting" something once \u2192 "purchased" or "acquired"
|
|
26505
|
+
- "got" \u2192 "purchased", "received as gift", "was given", "picked up"
|
|
26506
|
+
- "signed up" \u2192 "enrolled in", "registered for", "subscribed to"
|
|
26507
|
+
- "stopped getting" \u2192 "canceled", "unsubscribed from", "discontinued"
|
|
26497
26508
|
|
|
26498
26509
|
When the assistant interprets or confirms the user's vague language, prefer the assistant's precise terminology.
|
|
26499
26510
|
|
|
@@ -26578,16 +26589,16 @@ AVOIDING REPETITIVE OBSERVATIONS:
|
|
|
26578
26589
|
- Do NOT repeat the same observation across multiple turns if there is no new information.
|
|
26579
26590
|
- When the agent performs repeated similar actions (e.g., browsing files, running the same tool type multiple times), group them into a single parent observation with sub-bullets for each new result.
|
|
26580
26591
|
|
|
26581
|
-
Example
|
|
26582
|
-
*
|
|
26583
|
-
*
|
|
26584
|
-
*
|
|
26592
|
+
Example \u2014 BAD (repetitive):
|
|
26593
|
+
* \u{1F7E1} (14:30) Agent used view tool on src/auth.ts
|
|
26594
|
+
* \u{1F7E1} (14:31) Agent used view tool on src/users.ts
|
|
26595
|
+
* \u{1F7E1} (14:32) Agent used view tool on src/routes.ts
|
|
26585
26596
|
|
|
26586
|
-
Example
|
|
26587
|
-
*
|
|
26588
|
-
* -> viewed src/auth.ts
|
|
26589
|
-
* -> viewed src/users.ts
|
|
26590
|
-
* -> viewed src/routes.ts
|
|
26597
|
+
Example \u2014 GOOD (grouped):
|
|
26598
|
+
* \u{1F7E1} (14:30) Agent browsed source files for auth flow
|
|
26599
|
+
* -> viewed src/auth.ts \u2014 found token validation logic
|
|
26600
|
+
* -> viewed src/users.ts \u2014 found user lookup by email
|
|
26601
|
+
* -> viewed src/routes.ts \u2014 found middleware chain
|
|
26591
26602
|
|
|
26592
26603
|
Only add a new observation for a repeated action if the NEW result changes the picture.
|
|
26593
26604
|
|
|
@@ -26600,29 +26611,29 @@ COMPLETION TRACKING:
|
|
|
26600
26611
|
Completion observations are not just summaries. They are explicit memory signals to the assistant that a task, question, or subtask has been resolved.
|
|
26601
26612
|
Without clear completion markers, the assistant may forget that work is already finished and may repeat, reopen, or continue an already-completed task.
|
|
26602
26613
|
|
|
26603
|
-
Use
|
|
26614
|
+
Use \u2705 to answer: "What exactly is now done?"
|
|
26604
26615
|
Choose completion observations that help the assistant know what is finished and should not be reworked unless new information appears.
|
|
26605
26616
|
|
|
26606
|
-
Use
|
|
26617
|
+
Use \u2705 when:
|
|
26607
26618
|
- The user explicitly confirms something worked or was answered ("thanks, that fixed it", "got it", "perfect")
|
|
26608
26619
|
- The assistant provided a definitive, complete answer to a factual question and the user moved on
|
|
26609
26620
|
- A multi-step task reached its stated goal
|
|
26610
26621
|
- The user acknowledged receipt of requested information
|
|
26611
26622
|
- A concrete subtask, fix, deliverable, or implementation step became complete during ongoing work
|
|
26612
26623
|
|
|
26613
|
-
Do NOT use
|
|
26614
|
-
- The assistant merely responded
|
|
26624
|
+
Do NOT use \u2705 when:
|
|
26625
|
+
- The assistant merely responded \u2014 the user might follow up with corrections
|
|
26615
26626
|
- The topic is paused but not resolved ("I'll try that later")
|
|
26616
26627
|
- The user's reaction is ambiguous
|
|
26617
26628
|
|
|
26618
26629
|
FORMAT:
|
|
26619
26630
|
As a sub-bullet under the related observation group:
|
|
26620
|
-
*
|
|
26631
|
+
* \u{1F534} (14:30) User asked how to configure auth middleware
|
|
26621
26632
|
* -> Agent explained JWT setup with code example
|
|
26622
|
-
*
|
|
26633
|
+
* \u2705 User confirmed auth is working
|
|
26623
26634
|
|
|
26624
26635
|
Or as a standalone observation when closing out a broader task:
|
|
26625
|
-
*
|
|
26636
|
+
* \u2705 (14:45) Auth configuration task completed \u2014 user confirmed middleware is working
|
|
26626
26637
|
|
|
26627
26638
|
Completion observations should be terse but specific about WHAT was completed.
|
|
26628
26639
|
Prefer concrete resolved outcomes over abstract workflow status so the assistant remembers what is already done.`;
|
|
@@ -26639,28 +26650,28 @@ buildObserverOutputFormat();
|
|
|
26639
26650
|
*/
|
|
26640
26651
|
function buildObserverOutputFormat(extractors) {
|
|
26641
26652
|
return `Use priority levels:
|
|
26642
|
-
-
|
|
26643
|
-
-
|
|
26644
|
-
-
|
|
26645
|
-
-
|
|
26653
|
+
- \u{1F534} High: explicit user facts, preferences, unresolved goals, critical context
|
|
26654
|
+
- \u{1F7E1} Medium: project details, learned information, tool results
|
|
26655
|
+
- \u{1F7E2} Low: minor details, uncertain observations
|
|
26656
|
+
- \u2705 Completed: concrete task finished, question answered, issue resolved, goal achieved, or subtask completed in a way that helps the assistant know it is done
|
|
26646
26657
|
|
|
26647
26658
|
Group related observations (like tool sequences) by indenting:
|
|
26648
|
-
*
|
|
26659
|
+
* \u{1F534} (14:33) Agent debugging auth issue
|
|
26649
26660
|
* -> ran git status, found 3 modified files
|
|
26650
26661
|
* -> viewed auth.ts:45-60, found missing null check
|
|
26651
26662
|
* -> applied fix, tests now pass
|
|
26652
|
-
*
|
|
26663
|
+
* \u2705 Tests passing, auth issue resolved
|
|
26653
26664
|
|
|
26654
26665
|
Group observations by date. Within a date, list observations in the order the events happened (not by importance), each with 24-hour time.
|
|
26655
26666
|
|
|
26656
26667
|
<observations>
|
|
26657
26668
|
Date: Dec 4, 2025
|
|
26658
|
-
*
|
|
26659
|
-
*
|
|
26660
|
-
*
|
|
26669
|
+
* \u{1F534} (14:30) User prefers direct answers
|
|
26670
|
+
* \u{1F534} (14:31) Working on feature X
|
|
26671
|
+
* \u{1F7E1} (14:32) User might prefer dark mode
|
|
26661
26672
|
|
|
26662
26673
|
Date: Dec 5, 2025
|
|
26663
|
-
*
|
|
26674
|
+
* \u{1F534} (09:15) Continued work on feature X
|
|
26664
26675
|
</observations>
|
|
26665
26676
|
|
|
26666
26677
|
${buildExtractorOutputSections(extractors ?? []) || (extractors === void 0 ? `
|
|
@@ -26690,9 +26701,9 @@ const OBSERVER_GUIDELINES = `- Be specific enough for the assistant to act on
|
|
|
26690
26701
|
- If the agent calls tools, observe what was called, why, and what was learned
|
|
26691
26702
|
- When observing files with line numbers, include the line number if useful
|
|
26692
26703
|
- If the agent provides a detailed response, observe the contents so it could be repeated
|
|
26693
|
-
- Make sure you start each observation with a priority emoji (
|
|
26694
|
-
- Capture the user's words closely
|
|
26695
|
-
- Treat
|
|
26704
|
+
- Make sure you start each observation with a priority emoji (\u{1F534}, \u{1F7E1}, \u{1F7E2}) or a completion marker (\u2705)
|
|
26705
|
+
- 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}
|
|
26706
|
+
- Treat \u2705 as a memory signal that tells the assistant something is finished and should not be repeated unless new information changes it
|
|
26696
26707
|
- Make completion observations answer "What exactly is now done?"
|
|
26697
26708
|
- Prefer concrete resolved outcomes over meta-level workflow or bookkeeping updates
|
|
26698
26709
|
- When multiple concrete things were completed, capture the concrete completed work rather than collapsing it into a vague progress summary
|
|
@@ -26746,8 +26757,8 @@ For multi-thread output, wrap each thread's observations like this:
|
|
|
26746
26757
|
<observations>
|
|
26747
26758
|
<thread id="thread_id_1">
|
|
26748
26759
|
Date: Dec 4, 2025
|
|
26749
|
-
*
|
|
26750
|
-
*
|
|
26760
|
+
* \u{1F534} (14:30) User prefers direct answers
|
|
26761
|
+
* \u{1F534} (14:31) Working on feature X${currentTaskEnabled ? `
|
|
26751
26762
|
|
|
26752
26763
|
<current-task>
|
|
26753
26764
|
What the agent is currently working on in this thread
|
|
@@ -26760,7 +26771,7 @@ Hint for the agent's next message in this thread
|
|
|
26760
26771
|
|
|
26761
26772
|
<thread id="thread_id_2">
|
|
26762
26773
|
Date: Dec 5, 2025
|
|
26763
|
-
*
|
|
26774
|
+
* \u{1F534} (09:15) User asked about deployment${currentTaskEnabled ? `
|
|
26764
26775
|
|
|
26765
26776
|
<current-task>
|
|
26766
26777
|
Current task for this thread
|
|
@@ -27608,7 +27619,7 @@ function sanitizeObservationLines(observations) {
|
|
|
27608
27619
|
const lines = observations.split("\n");
|
|
27609
27620
|
let changed = false;
|
|
27610
27621
|
for (let i = 0; i < lines.length; i++) if (lines[i].length > MAX_OBSERVATION_LINE_CHARS) {
|
|
27611
|
-
lines[i] = safeSlice(lines[i], MAX_OBSERVATION_LINE_CHARS) + "
|
|
27622
|
+
lines[i] = safeSlice(lines[i], MAX_OBSERVATION_LINE_CHARS) + " \u2026 [truncated]";
|
|
27612
27623
|
changed = true;
|
|
27613
27624
|
}
|
|
27614
27625
|
return changed ? lines.join("\n") : observations;
|
|
@@ -27832,8 +27843,8 @@ function extractCurrentTask(observations) {
|
|
|
27832
27843
|
*/
|
|
27833
27844
|
function optimizeObservationsForContext(observations) {
|
|
27834
27845
|
let optimized = stripEphemeralAnchorIds(observations);
|
|
27835
|
-
optimized = optimized.replace(
|
|
27836
|
-
optimized = optimized.replace(
|
|
27846
|
+
optimized = optimized.replace(/\uD83D\uDFE1\s*/g, "");
|
|
27847
|
+
optimized = optimized.replace(/\uD83D\uDFE2\s*/g, "");
|
|
27837
27848
|
optimized = optimized.replace(/\s*->\s*/g, " ");
|
|
27838
27849
|
optimized = optimized.replace(/ +/g, " ");
|
|
27839
27850
|
optimized = optimized.replace(/\n{3,}/g, "\n\n");
|
|
@@ -30119,8 +30130,8 @@ const updateWorkingMemoryTool = (memoryConfig) => {
|
|
|
30119
30130
|
}
|
|
30120
30131
|
const usesMergeSemantics = Boolean(schema);
|
|
30121
30132
|
const useStateSignals = memoryConfig?.workingMemory?.useStateSignals === true;
|
|
30122
|
-
const stateSignalsPreamble = `The current working memory state is delivered to you each turn by the system inside a <working-memory>...</working-memory> block. That block is system-emitted state, NOT something the user typed
|
|
30123
|
-
const description = schema ? useStateSignals ? `${stateSignalsPreamble} Data is merged with existing memory
|
|
30133
|
+
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.`;
|
|
30134
|
+
const description = schema ? useStateSignals ? `${stateSignalsPreamble} Data is merged with existing memory \u2014 only include fields you want to add or update.` : `Update the working memory with new information. Data is merged with existing memory - only include fields you want to add or update. To preserve existing data, omit the field entirely. Arrays are replaced entirely when provided, so pass the complete array or omit it to keep the existing values.` : useStateSignals ? `${stateSignalsPreamble} Pass the full updated Markdown blob as a string in the memory field.` : `Update the working memory with new information. Any data not included will be overwritten. Always pass data as string to the memory field. Never pass an object.`;
|
|
30124
30135
|
return (0, _mastra_core_tools.createTool)({
|
|
30125
30136
|
id: "update-working-memory",
|
|
30126
30137
|
description,
|
|
@@ -31151,8 +31162,8 @@ async function pageGroups({ om, threadId, resourceId, groupId, recordId, directi
|
|
|
31151
31162
|
})).count > 0;
|
|
31152
31163
|
const hasLater = direction === "before" || hasMore;
|
|
31153
31164
|
const newer = hasLater ? null : await newerMessagesNote(page.at(-1).group, countNewerMessages, pagingThreadId);
|
|
31154
|
-
text.unshift(hasEarlier ?
|
|
31155
|
-
text.push(hasLater ?
|
|
31165
|
+
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");
|
|
31166
|
+
text.push(hasLater ? `\u2014 Browse later: ${pagingCall(page.at(-1).group.id, "after", pagingThreadId, page.at(-1).record.id)} \u2014` : newer ? `\u2014 End of observation history for this thread. ${newer} \u2014` : "\u2014 End of retained observation history for this thread. \u2014");
|
|
31156
31167
|
text.unshift(`### Observation page\nThread: ${threadTitle || "(untitled)"}\nShowing ${page.length} groups ${requestedDirection === void 0 ? "starting at" : `strictly ${direction}`} \`${groupId}\` (oldest first).`);
|
|
31157
31168
|
return {
|
|
31158
31169
|
results: text.join("\n\n"),
|
|
@@ -31340,7 +31351,7 @@ async function listThreadsForResource({ memory, resourceId, currentThreadId, pag
|
|
|
31340
31351
|
const title = thread.title || "(untitled)";
|
|
31341
31352
|
const updated = formatTimestamp(thread.updatedAt);
|
|
31342
31353
|
const created = formatTimestamp(thread.createdAt);
|
|
31343
|
-
const marker = isCurrent ? "
|
|
31354
|
+
const marker = isCurrent ? " \u2190 current" : "";
|
|
31344
31355
|
lines.push(`- **${title}**${marker}`);
|
|
31345
31356
|
lines.push(` id: ${thread.id}`);
|
|
31346
31357
|
lines.push(` updated: ${updated} | created: ${created}`);
|
|
@@ -31519,7 +31530,7 @@ async function searchMessagesForResource({ memory, om, resourceId, currentThread
|
|
|
31519
31530
|
const groupLine = match.groupId ? `- observation group: ${groupCursor(match.groupId, match.recordId)}` : void 0;
|
|
31520
31531
|
const scoreLine = `- score: ${match.score.toFixed(2)}`;
|
|
31521
31532
|
const prev = i > 0 ? ordered[i - 1].match : void 0;
|
|
31522
|
-
if (om && prev?.groupId && match.groupId && prev.threadId === match.threadId) sections.push(
|
|
31533
|
+
if (om && prev?.groupId && match.groupId && prev.threadId === match.threadId) sections.push(`\u2014 Observation groups may be hidden between these results; continue with ${pagingCall(prev.groupId, "after", includeThreadId ? prev.threadId : void 0, prev.recordId)} \u2014`);
|
|
31523
31534
|
if (suppression) {
|
|
31524
31535
|
sections.push(`${groupLine}\n thread: ${match.threadId}; ${suppression}`);
|
|
31525
31536
|
continue;
|
|
@@ -32074,7 +32085,7 @@ async function recallAttachmentView({ memory, threadId, resourceId, cursor, part
|
|
|
32074
32085
|
const partType = rawPart?.type;
|
|
32075
32086
|
if (!rawPart || partType !== "image" && partType !== "file") return { messages: `Part ${partIndex} of message ${cursor} is ${rawPart ? `a ${partType ?? "unknown"}-type part` : "missing"}, not an attachment. Call recall with the same cursor and partIndex without viewAttachment to read it.` };
|
|
32076
32087
|
const resolvedAttachment = resolveViewableAttachment(rawPart);
|
|
32077
|
-
if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)}
|
|
32088
|
+
if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)} \u2014 ${resolvedAttachment.note}` };
|
|
32078
32089
|
return { content: [{
|
|
32079
32090
|
type: "text",
|
|
32080
32091
|
text: formatAttachmentPart(partType, rawPart)
|
|
@@ -32477,7 +32488,7 @@ const recallTool = (_memoryConfig, options) => {
|
|
|
32477
32488
|
if (!thread) return { error: "Could not resolve current thread." };
|
|
32478
32489
|
if (isResourceScope && resourceId && thread.resourceId !== resourceId) throw new Error("Thread does not belong to the active resource");
|
|
32479
32490
|
return {
|
|
32480
|
-
threads: `- **${thread.title || "(untitled)"}**
|
|
32491
|
+
threads: `- **${thread.title || "(untitled)"}** \u2190 current\n id: ${thread.id}\n updated: ${formatTimestamp(thread.updatedAt)} | created: ${formatTimestamp(thread.createdAt)}`,
|
|
32481
32492
|
count: 1,
|
|
32482
32493
|
page: 0,
|
|
32483
32494
|
hasMore: false
|
|
@@ -33237,9 +33248,9 @@ const suggestedResponseInstructions = `Hint for the agent's immediate next messa
|
|
|
33237
33248
|
- "The assistant should wait for the user to respond before continuing."
|
|
33238
33249
|
- Call the view tool on src/example.ts to continue debugging.`;
|
|
33239
33250
|
const threadTitleInstructions = `A short, noun-phrase title for this conversation (2-5 words). Examples:
|
|
33240
|
-
- "Auth bug fix"
|
|
33241
|
-
- "Dark mode toggle"
|
|
33242
|
-
- "Deployment pipeline setup"
|
|
33251
|
+
- "Auth bug fix" \u2014 not "Fixing the auth bug"
|
|
33252
|
+
- "Dark mode toggle" \u2014 not "User wants dark mode toggle added"
|
|
33253
|
+
- "Deployment pipeline setup" \u2014 not "Setting up deployment pipeline for project"
|
|
33243
33254
|
Only update when the topic meaningfully changes.`;
|
|
33244
33255
|
function createCurrentTaskExtractor() {
|
|
33245
33256
|
return new Extractor({
|
|
@@ -34316,7 +34327,7 @@ var SyncObservationStrategy = class extends ObservationStrategy {
|
|
|
34316
34327
|
failures: result.extractionFailures,
|
|
34317
34328
|
previousValues: this.priorExtractedValues,
|
|
34318
34329
|
rawObservations: result.observations,
|
|
34319
|
-
recentMessages: formatMessagesForObserver(this.opts.messages, {
|
|
34330
|
+
recentMessages: () => formatMessagesForObserver(this.opts.messages, {
|
|
34320
34331
|
maxPartLength: 500,
|
|
34321
34332
|
timeZone: this.opts.record.observedTimezone
|
|
34322
34333
|
}),
|
|
@@ -34541,7 +34552,7 @@ var AsyncBufferObservationStrategy = class extends ObservationStrategy {
|
|
|
34541
34552
|
failures: result.extractionFailures,
|
|
34542
34553
|
previousValues: this.priorExtractedValues,
|
|
34543
34554
|
rawObservations: result.observations,
|
|
34544
|
-
recentMessages: formatMessagesForObserver(messages, {
|
|
34555
|
+
recentMessages: () => formatMessagesForObserver(messages, {
|
|
34545
34556
|
maxPartLength: 500,
|
|
34546
34557
|
timeZone: this.opts.record.observedTimezone
|
|
34547
34558
|
}),
|
|
@@ -34971,7 +34982,7 @@ var ResourceScopedObservationStrategy = class extends ObservationStrategy {
|
|
|
34971
34982
|
failures: result.extractionFailures,
|
|
34972
34983
|
previousValues,
|
|
34973
34984
|
rawObservations: result.observations,
|
|
34974
|
-
recentMessages: formatMessagesForObserver(threadMessages, {
|
|
34985
|
+
recentMessages: () => formatMessagesForObserver(threadMessages, {
|
|
34975
34986
|
maxPartLength: 500,
|
|
34976
34987
|
timeZone: this.opts.record.observedTimezone
|
|
34977
34988
|
}),
|
|
@@ -35304,7 +35315,7 @@ var ObservationStep = class {
|
|
|
35304
35315
|
}
|
|
35305
35316
|
/** Step context from prepare(). Throws if prepare() hasn't been called. */
|
|
35306
35317
|
get context() {
|
|
35307
|
-
if (!this._context) throw new Error("Step not prepared yet
|
|
35318
|
+
if (!this._context) throw new Error("Step not prepared yet \u2014 call prepare() first");
|
|
35308
35319
|
return this._context;
|
|
35309
35320
|
}
|
|
35310
35321
|
/**
|
|
@@ -35724,7 +35735,7 @@ var ObservationStep = class {
|
|
|
35724
35735
|
const messagesToSeal = messageToSeal ? [messageToSeal] : [];
|
|
35725
35736
|
this.turn.abortSignal?.throwIfAborted();
|
|
35726
35737
|
om.sealMessagesForBuffering(messagesToSeal);
|
|
35727
|
-
if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation
|
|
35738
|
+
if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation \u2014 step-0 seeded response message holds the active id");
|
|
35728
35739
|
else try {
|
|
35729
35740
|
await this.turn.hooks?.onSyncObservationComplete?.();
|
|
35730
35741
|
} catch (error) {
|
|
@@ -35875,12 +35886,12 @@ var ObservationTurn = class {
|
|
|
35875
35886
|
messageList;
|
|
35876
35887
|
/** The current cached record. Refreshed after mutations (activate/observe/reflect). */
|
|
35877
35888
|
get record() {
|
|
35878
|
-
if (!this._record) throw new Error("Turn not started
|
|
35889
|
+
if (!this._record) throw new Error("Turn not started \u2014 call start() first");
|
|
35879
35890
|
return this._record;
|
|
35880
35891
|
}
|
|
35881
35892
|
/** The context loaded during start(). */
|
|
35882
35893
|
get context() {
|
|
35883
|
-
if (!this._context) throw new Error("Turn not started
|
|
35894
|
+
if (!this._context) throw new Error("Turn not started \u2014 call start() first");
|
|
35884
35895
|
return this._context;
|
|
35885
35896
|
}
|
|
35886
35897
|
/** Whether the turn has been ended and can no longer accept steps. */
|
|
@@ -35949,7 +35960,7 @@ var ObservationTurn = class {
|
|
|
35949
35960
|
* (its output messages will be saved at the start of the new step's prepare()).
|
|
35950
35961
|
*/
|
|
35951
35962
|
step(stepNumber) {
|
|
35952
|
-
if (!this._started) throw new Error("Turn not started
|
|
35963
|
+
if (!this._started) throw new Error("Turn not started \u2014 call start() first");
|
|
35953
35964
|
if (this._ended) throw new Error("Turn already ended");
|
|
35954
35965
|
this._currentStep = new ObservationStep(this, stepNumber);
|
|
35955
35966
|
return this._currentStep;
|
|
@@ -36172,8 +36183,8 @@ When consolidating observations:
|
|
|
36172
36183
|
- Keep what the user explicitly said they have never done, do not know, or refused, and keep every stated preference, rule, and instruction with its meaning intact
|
|
36173
36184
|
- Prefer many short factual lines over prose summaries. Do not replace facts with generalities like "discussed travel plans"
|
|
36174
36185
|
- Combine related items where it makes sense (e.g., "agent called view tool 5 times on file x")
|
|
36175
|
-
- Preserve
|
|
36176
|
-
- Preserve the concrete resolved outcome captured by
|
|
36186
|
+
- Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
|
|
36187
|
+
- Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
|
|
36177
36188
|
- Condense the wording of older observations more than recent ones, but keep their facts
|
|
36178
36189
|
|
|
36179
36190
|
CRITICAL: USER ASSERTIONS vs QUESTIONS
|
|
@@ -36195,23 +36206,23 @@ When observations contain <thread id="..."> sections:
|
|
|
36195
36206
|
Example input:
|
|
36196
36207
|
<thread id="thread-1">
|
|
36197
36208
|
Date: Dec 4, 2025
|
|
36198
|
-
*
|
|
36199
|
-
*
|
|
36209
|
+
* \u{1F534} (14:30) User prefers TypeScript
|
|
36210
|
+
* \u{1F7E1} (14:35) Working on auth feature
|
|
36200
36211
|
</thread>
|
|
36201
36212
|
<thread id="thread-2">
|
|
36202
36213
|
Date: Dec 4, 2025
|
|
36203
|
-
*
|
|
36204
|
-
*
|
|
36214
|
+
* \u{1F534} (15:00) User prefers TypeScript
|
|
36215
|
+
* \u{1F7E1} (15:05) Debugging API endpoint
|
|
36205
36216
|
</thread>
|
|
36206
36217
|
|
|
36207
36218
|
Example output (consolidated):
|
|
36208
36219
|
Date: Dec 4, 2025
|
|
36209
|
-
*
|
|
36220
|
+
* \u{1F534} (14:30) User prefers TypeScript
|
|
36210
36221
|
<thread id="thread-1">
|
|
36211
|
-
*
|
|
36222
|
+
* \u{1F7E1} (14:35) Working on auth feature
|
|
36212
36223
|
</thread>
|
|
36213
36224
|
<thread id="thread-2">
|
|
36214
|
-
*
|
|
36225
|
+
* \u{1F7E1} (15:05) Debugging API endpoint
|
|
36215
36226
|
</thread>
|
|
36216
36227
|
|
|
36217
36228
|
=== OUTPUT FORMAT ===
|
|
@@ -36242,8 +36253,8 @@ Please re-process with slightly more compression:
|
|
|
36242
36253
|
- Memory is getting long - use a more condensed style throughout
|
|
36243
36254
|
- Combine related items more aggressively but do not lose important specific details of names, places, events, and people
|
|
36244
36255
|
- Combine repeated similar tool calls (e.g. multiple file views, searches, or edits in the same area) into a single summary line describing what was explored/changed and the outcome
|
|
36245
|
-
- Preserve
|
|
36246
|
-
- Preserve the concrete resolved outcome captured by
|
|
36256
|
+
- Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
|
|
36257
|
+
- Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
|
|
36247
36258
|
|
|
36248
36259
|
Aim for a 8/10 detail level.
|
|
36249
36260
|
`,
|
|
@@ -36259,8 +36270,8 @@ Please re-process with much more aggressive compression:
|
|
|
36259
36270
|
- Combine related items aggressively but do not lose important specific details of names, places, events, and people
|
|
36260
36271
|
- Combine repeated similar tool calls (e.g. multiple file views, searches, or edits in the same area) into a single summary line describing what was explored/changed and the outcome
|
|
36261
36272
|
- If the same file or module is mentioned across many observations, merge into one entry covering the full arc
|
|
36262
|
-
- Preserve
|
|
36263
|
-
- Preserve the concrete resolved outcome captured by
|
|
36273
|
+
- Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
|
|
36274
|
+
- Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
|
|
36264
36275
|
- Remove redundant information and merge overlapping observations
|
|
36265
36276
|
|
|
36266
36277
|
Aim for a 6/10 detail level.
|
|
@@ -36271,14 +36282,14 @@ Aim for a 6/10 detail level.
|
|
|
36271
36282
|
Your previous reflections have failed to compress sufficiently after multiple attempts.
|
|
36272
36283
|
|
|
36273
36284
|
Please re-process with maximum compression:
|
|
36274
|
-
- Summarize the oldest observations (first 50-70%) into brief high-level paragraphs
|
|
36285
|
+
- Summarize the oldest observations (first 50-70%) into brief high-level paragraphs \u2014 only key facts, decisions, and outcomes
|
|
36275
36286
|
- For the most recent observations (last 30-50%), retain important details but still use a condensed style
|
|
36276
|
-
- Ruthlessly merge related observations
|
|
36277
|
-
- Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries
|
|
36278
|
-
- Drop procedural details (tool calls, retries, intermediate steps)
|
|
36287
|
+
- Ruthlessly merge related observations \u2014 if 10 observations are about the same topic, combine into 1-2 lines
|
|
36288
|
+
- Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries \u2014 drop individual steps entirely
|
|
36289
|
+
- Drop procedural details (tool calls, retries, intermediate steps) \u2014 keep only final outcomes
|
|
36279
36290
|
- Drop observations that are no longer relevant or have been superseded by newer information
|
|
36280
|
-
- Preserve
|
|
36281
|
-
- Preserve the concrete resolved outcome captured by
|
|
36291
|
+
- Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
|
|
36292
|
+
- Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
|
|
36282
36293
|
- Preserve: names, dates, decisions, errors, user preferences, and architectural choices
|
|
36283
36294
|
|
|
36284
36295
|
Aim for a 4/10 detail level.
|
|
@@ -36289,14 +36300,14 @@ Aim for a 4/10 detail level.
|
|
|
36289
36300
|
Multiple compression attempts have failed. The content may already be dense from a prior reflection.
|
|
36290
36301
|
|
|
36291
36302
|
You MUST dramatically reduce the number of observations while keeping the standard observation format (date groups with bullet points and priority emojis):
|
|
36292
|
-
- Tool call observations are the biggest source of bloat. Collapse ALL tool call sequences into outcome-only observations
|
|
36293
|
-
- Never preserve individual tool calls (viewed file X, searched for Y, ran build)
|
|
36303
|
+
- 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")
|
|
36304
|
+
- Never preserve individual tool calls (viewed file X, searched for Y, ran build) \u2014 only preserve what was discovered or accomplished
|
|
36294
36305
|
- Consolidate many related observations into single, more generic observations
|
|
36295
36306
|
- Merge all same-day date groups into at most 2-3 date groups per day
|
|
36296
36307
|
- For older content, each topic or task should be at most 1-2 observations capturing the key outcome
|
|
36297
36308
|
- For recent content, retain more detail but still merge related items aggressively
|
|
36298
36309
|
- If multiple observations describe incremental progress on the same task, keep only the final state
|
|
36299
|
-
- Preserve
|
|
36310
|
+
- Preserve \u2705 completion markers and their outcomes but merge related completions into fewer lines
|
|
36300
36311
|
- Preserve: user preferences, key decisions, architectural choices, and unresolved issues
|
|
36301
36312
|
|
|
36302
36313
|
Aim for a 2/10 detail level. Fewer, more generic observations are better than many specific ones that exceed the budget.
|
|
@@ -36720,7 +36731,7 @@ var ReflectorRunner = class {
|
|
|
36720
36731
|
operationType: "reflection",
|
|
36721
36732
|
startedAt: streamContext.startedAt,
|
|
36722
36733
|
tokensAttempted: originalTokens,
|
|
36723
|
-
error: `Did not compress below threshold (${originalTokens}
|
|
36734
|
+
error: `Did not compress below threshold (${originalTokens} \u2192 ${reflectedTokens}, target: ${targetThreshold}), retrying at level ${currentLevel + 1}`,
|
|
36724
36735
|
retrying: true,
|
|
36725
36736
|
recordId: streamContext.recordId,
|
|
36726
36737
|
threadId: streamContext.threadId
|
|
@@ -36750,7 +36761,7 @@ var ReflectorRunner = class {
|
|
|
36750
36761
|
}
|
|
36751
36762
|
currentLevel = Math.min(currentLevel + 1, maxLevel);
|
|
36752
36763
|
}
|
|
36753
|
-
if (observations.trim().length > 0 && parsed.observations.trim().length === 0) throw new Error(`Reflector produced empty output after ${attemptNumber} attempt(s)${parsed.degenerate ? " (degenerate repetition)" : ""}
|
|
36764
|
+
if (observations.trim().length > 0 && parsed.observations.trim().length === 0) throw new Error(`Reflector produced empty output after ${attemptNumber} attempt(s)${parsed.degenerate ? " (degenerate repetition)" : ""} \u2014 refusing to commit an empty reflection over ${originalTokens} observation tokens`);
|
|
36754
36765
|
const structuredExtraction = await extractStructuredValues({
|
|
36755
36766
|
agent,
|
|
36756
36767
|
source: "reflector",
|
|
@@ -36891,7 +36902,7 @@ var ReflectorRunner = class {
|
|
|
36891
36902
|
const reflectedObservationLineCount = linesToReflect;
|
|
36892
36903
|
const sliceTokenEstimate = Math.round(avgTokensPerLine * linesToReflect);
|
|
36893
36904
|
const compressionTarget = Math.round(sliceTokenEstimate * .75);
|
|
36894
|
-
omDebug(`[OM:reflect] doAsyncBufferedReflection: slicing observations for reflection
|
|
36905
|
+
omDebug(`[OM:reflect] doAsyncBufferedReflection: slicing observations for reflection \u2014 totalLines=${totalLines}, avgTokPerLine=${avgTokensPerLine.toFixed(1)}, activationPointTokens=${activationPointTokens}, linesToReflect=${linesToReflect}/${totalLines}, sliceTokenEstimate=${sliceTokenEstimate}, compressionTarget=${compressionTarget}`);
|
|
36895
36906
|
omDebug(`[OM:reflect] doAsyncBufferedReflection: starting reflector call, recordId=${currentRecord.id}, observationTokens=${sliceTokenEstimate}, compressionTarget=${compressionTarget} (inputTokens), activeObsLength=${activeObservations.length}, reflectedLineCount=${reflectedObservationLineCount}`);
|
|
36896
36907
|
if (writer) {
|
|
36897
36908
|
const startMarker = createBufferingStartMarker({
|
|
@@ -37063,7 +37074,7 @@ var ReflectorRunner = class {
|
|
|
37063
37074
|
const unreflectedTailTokens = unreflectedContent ? this.tokenCounter.countObservations(unreflectedContent) : 0;
|
|
37064
37075
|
const bufferedReflectionTokens = freshRecord.bufferedReflectionTokens ?? 0;
|
|
37065
37076
|
if (unreflectedTailTokens < bufferedReflectionTokens) {
|
|
37066
|
-
omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation
|
|
37077
|
+
omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation \u2014 unreflectedTailTokens=${unreflectedTailTokens} < bufferedReflectionTokens=${bufferedReflectionTokens}; keeping buffer for threshold activation`);
|
|
37067
37078
|
return {
|
|
37068
37079
|
status: "suppressed",
|
|
37069
37080
|
reason: "composition"
|
|
@@ -37074,7 +37085,7 @@ var ReflectorRunner = class {
|
|
|
37074
37085
|
const regularActivationTarget = reflectThreshold * (1 - bufferActivation);
|
|
37075
37086
|
const minCombinedTokens = Math.round(regularActivationTarget * EARLY_ACTIVATION_SIZE_FLOOR_RATIO);
|
|
37076
37087
|
if (combinedTokenCount < minCombinedTokens) {
|
|
37077
|
-
omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation
|
|
37088
|
+
omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation \u2014 combinedTokenCount=${combinedTokenCount} < minCombinedTokens=${minCombinedTokens} (${EARLY_ACTIVATION_SIZE_FLOOR_RATIO * 100}% of regular activation target ${Math.round(regularActivationTarget)}, threshold=${reflectThreshold}, bufferActivation=${bufferActivation}); keeping buffer for threshold activation`);
|
|
37078
37089
|
return {
|
|
37079
37090
|
status: "suppressed",
|
|
37080
37091
|
reason: "size"
|
|
@@ -37203,7 +37214,7 @@ var ReflectorRunner = class {
|
|
|
37203
37214
|
omDebug(`[OM:reflect] isReflecting=true and active in this process, skipping`);
|
|
37204
37215
|
return;
|
|
37205
37216
|
}
|
|
37206
|
-
omDebug(`[OM:reflect] isReflecting=true but NOT active in this process
|
|
37217
|
+
omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
|
|
37207
37218
|
await this.storage.setReflectingFlag(record.id, false);
|
|
37208
37219
|
}
|
|
37209
37220
|
if (this.buffering.isAsyncReflectionEnabled()) {
|
|
@@ -37217,15 +37228,15 @@ var ReflectorRunner = class {
|
|
|
37217
37228
|
else {
|
|
37218
37229
|
const activationPoint = reflectThreshold * this.reflectionConfig.bufferActivation;
|
|
37219
37230
|
if (observationTokens < activationPoint) {
|
|
37220
|
-
omDebug(`[OM:reflect] skipping async reflection
|
|
37231
|
+
omDebug(`[OM:reflect] skipping async reflection \u2014 observationTokens (${observationTokens}) below activation point (${activationPoint}), triggered by ${activationTriggeredBy}`);
|
|
37221
37232
|
return;
|
|
37222
37233
|
}
|
|
37223
37234
|
const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
|
|
37224
37235
|
if (this.buffering.isAsyncBufferingInProgress(bufferKey) || BufferingCoordinator.lastBufferedBoundary.has(bufferKey)) {
|
|
37225
|
-
omDebug(`[OM:reflect] skipping async reflection
|
|
37236
|
+
omDebug(`[OM:reflect] skipping async reflection \u2014 reflection buffer already active or present for ${bufferKey}`);
|
|
37226
37237
|
return;
|
|
37227
37238
|
}
|
|
37228
|
-
omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter})
|
|
37239
|
+
omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) \u2014 starting background reflection`);
|
|
37229
37240
|
this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
|
|
37230
37241
|
return;
|
|
37231
37242
|
}
|
|
@@ -37233,7 +37244,7 @@ var ReflectorRunner = class {
|
|
|
37233
37244
|
if (activationTriggeredBy === "threshold") {
|
|
37234
37245
|
const suppressedAtTokens = this.syncReflectionSuppression.get(lockKey);
|
|
37235
37246
|
if (suppressedAtTokens !== void 0 && observationTokens === suppressedAtTokens) {
|
|
37236
|
-
omDebug(`[OM:reflect] skipping sync reflection
|
|
37247
|
+
omDebug(`[OM:reflect] skipping sync reflection \u2014 observations unchanged at ${observationTokens} tokens since the last unproductive attempt; retrying once they change`);
|
|
37237
37248
|
return;
|
|
37238
37249
|
}
|
|
37239
37250
|
}
|
|
@@ -38076,7 +38087,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
38076
38087
|
const asyncBufferingDisabled = config.observation?.bufferTokens === false || config.scope === "resource" && !userExplicitlyConfiguredAsync;
|
|
38077
38088
|
if (isSharedBudget && !asyncBufferingDisabled) {
|
|
38078
38089
|
if (userExplicitlyConfiguredAsync) throw new Error("shareTokenBudget requires async buffering to be disabled (this is a temporary limitation). Add observation: { bufferTokens: false } to your config:\n\n observationalMemory: {\n shareTokenBudget: true,\n observation: { bufferTokens: false },\n }\n\nRemove any other async buffering settings (bufferTokens, bufferActivation, blockAfter).");
|
|
38079
|
-
else throw new Error("shareTokenBudget requires async buffering to be disabled (this is a temporary limitation). Add observation: { bufferTokens: false } to your config:\n\n observationalMemory: {\n shareTokenBudget: true,\n observation: { bufferTokens: false },\n }\n\nAsync buffering is enabled by default
|
|
38090
|
+
else throw new Error("shareTokenBudget requires async buffering to be disabled (this is a temporary limitation). Add observation: { bufferTokens: false } to your config:\n\n observationalMemory: {\n shareTokenBudget: true,\n observation: { bufferTokens: false },\n }\n\nAsync buffering is enabled by default \u2014 this opt-out is only needed when using shareTokenBudget.");
|
|
38080
38091
|
}
|
|
38081
38092
|
const observationActivateAfterIdle = config.observation?.activateAfterIdle ?? config.activateAfterIdle;
|
|
38082
38093
|
const observationActivateAfterIdlePath = config.observation?.activateAfterIdle !== void 0 ? "observation.activateAfterIdle" : "activateAfterIdle";
|
|
@@ -38173,7 +38184,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
38173
38184
|
hasWarnedResourceScopeDeprecation = true;
|
|
38174
38185
|
console.warn("[Mastra] Observational memory `scope: 'resource'` is deprecated and will be removed in a future release because it works much worse than thread scope for prompt caching and agent understanding. Remove `scope` to use the default thread scope, and enable `retrieval` for cross-thread recall. See https://mastra.ai/docs/memory/observational-memory#resource-scope-deprecated");
|
|
38175
38186
|
}
|
|
38176
|
-
omDebug(`[OM:init] new ObservationalMemory instance created
|
|
38187
|
+
omDebug(`[OM:init] new ObservationalMemory instance created \u2014 scope=${this.scope}, messageTokens=${JSON.stringify(this.observationConfig.messageTokens)}, obsAsyncEnabled=${this.buffering.isAsyncObservationEnabled()}, bufferTokens=${this.observationConfig.bufferTokens}, bufferActivation=${this.observationConfig.bufferActivation}, blockAfter=${this.observationConfig.blockAfter}, reflectionTokens=${this.reflectionConfig.observationTokens}, refAsyncEnabled=${this.buffering.isAsyncReflectionEnabled()}, refAsyncActivation=${this.reflectionConfig.bufferActivation}, refBlockAfter=${this.reflectionConfig.blockAfter}`);
|
|
38177
38188
|
}
|
|
38178
38189
|
__registerMastra(mastra) {
|
|
38179
38190
|
this.mastra = mastra;
|
|
@@ -38454,7 +38465,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
38454
38465
|
threadId: null,
|
|
38455
38466
|
resourceId: resourceId ?? threadId
|
|
38456
38467
|
};
|
|
38457
|
-
if (!threadId) throw new Error("ObservationalMemory (scope: 'thread') requires a threadId, but received an empty value. This is a bug
|
|
38468
|
+
if (!threadId) throw new Error("ObservationalMemory (scope: 'thread') requires a threadId, but received an empty value. This is a bug \u2014 getThreadContext should have caught this earlier.");
|
|
38458
38469
|
return {
|
|
38459
38470
|
threadId,
|
|
38460
38471
|
resourceId: resourceId ?? threadId
|
|
@@ -38765,7 +38776,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
38765
38776
|
const isImportant = new Array(totalCount);
|
|
38766
38777
|
for (let i = 0; i < totalCount; i++) {
|
|
38767
38778
|
lineTokens[i] = this.tokenCounter.countString(lines[i]);
|
|
38768
|
-
isImportant[i] = lines[i].includes("
|
|
38779
|
+
isImportant[i] = lines[i].includes("\u{1F534}") || lines[i].includes("\u2705");
|
|
38769
38780
|
}
|
|
38770
38781
|
const suffixTokens = new Array(totalCount + 1);
|
|
38771
38782
|
suffixTokens[totalCount] = 0;
|
|
@@ -39098,7 +39109,7 @@ ${formattedMessages}
|
|
|
39098
39109
|
resourceId: freshRecord.resourceId ?? void 0
|
|
39099
39110
|
});
|
|
39100
39111
|
} catch (err) {
|
|
39101
|
-
omError("[OM] Failed to persist sealed messages before buffering
|
|
39112
|
+
omError("[OM] Failed to persist sealed messages before buffering \u2014 skipping observation cycle", err);
|
|
39102
39113
|
return;
|
|
39103
39114
|
}
|
|
39104
39115
|
const cycleId = `buffer-obs-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
|
|
@@ -40248,7 +40259,7 @@ ${formattedMessages}
|
|
|
40248
40259
|
usage: void 0
|
|
40249
40260
|
};
|
|
40250
40261
|
}
|
|
40251
|
-
omDebug(`[OM:reflect] isReflecting=true but NOT active in this process
|
|
40262
|
+
omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
|
|
40252
40263
|
await this.storage.setReflectingFlag(record.id, false);
|
|
40253
40264
|
}
|
|
40254
40265
|
await this.storage.setReflectingFlag(record.id, true);
|
|
@@ -40483,7 +40494,7 @@ ${formattedMessages}
|
|
|
40483
40494
|
// src/processors/observational-memory/temporal-markers.ts
|
|
40484
40495
|
const TEMPORAL_GAP_REMINDER_TYPE = "temporal-gap";
|
|
40485
40496
|
function getTemporalGapReminderText(gapText, timestamp) {
|
|
40486
|
-
return `${gapText}
|
|
40497
|
+
return `${gapText} \u2014 ${formatTemporalTimestamp(new Date(timestamp))}`;
|
|
40487
40498
|
}
|
|
40488
40499
|
function getTemporalGapReminderMetadata(message, gapText, gapMs, timestamp) {
|
|
40489
40500
|
const formattedTimestamp = formatTemporalTimestamp(new Date(timestamp));
|
|
@@ -40705,14 +40716,14 @@ var ObservationalMemoryProcessor = class {
|
|
|
40705
40716
|
omDebug(`[OM:processInputStep:ENTER] step=${stepNumber}, hasMastraMemory=${!!requestContext?.get("MastraMemory")}, hasMemoryInfo=${!!messageList?.serialize()?.memoryInfo?.threadId}`);
|
|
40706
40717
|
const context = this.engine.getThreadContext(requestContext, messageList);
|
|
40707
40718
|
if (!context) {
|
|
40708
|
-
omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null
|
|
40719
|
+
omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null \u2014 returning early`);
|
|
40709
40720
|
return messageList;
|
|
40710
40721
|
}
|
|
40711
40722
|
const gatewayMemoryManaged = await isGatewayMemoryManaged(model);
|
|
40712
40723
|
state[GATEWAY_STATE_KEY] = gatewayMemoryManaged;
|
|
40713
40724
|
if (gatewayMemoryManaged) {
|
|
40714
40725
|
await this.endActiveTurn(state);
|
|
40715
|
-
omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory
|
|
40726
|
+
omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory \u2014 skipping local processing`);
|
|
40716
40727
|
return messageList;
|
|
40717
40728
|
}
|
|
40718
40729
|
const { threadId, resourceId } = context;
|
|
@@ -40933,7 +40944,7 @@ var ObservationalMemoryProcessor = class {
|
|
|
40933
40944
|
if (!context) return;
|
|
40934
40945
|
if ((0, _mastra_core_memory.parseMemoryRequestContext)(requestContext)?.memoryConfig?.readOnly) return;
|
|
40935
40946
|
state[CONTEXT_OVERFLOW_STEP_KEY] = stepNumber;
|
|
40936
|
-
omDebug(`[OM:processAPIError] context overflow at step ${stepNumber}
|
|
40947
|
+
omDebug(`[OM:processAPIError] context overflow at step ${stepNumber} \u2014 observing pending messages`);
|
|
40937
40948
|
const { threadId, resourceId } = context;
|
|
40938
40949
|
await this.engine.waitForBuffering(threadId, resourceId, void 0, args.abortSignal);
|
|
40939
40950
|
const messages = getObservableMessages(messageList);
|