@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.
@@ -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 — pass \`threadId\` to read another thread and a \`cursor\` from the source message range.
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 — 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
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 — pass \`threadId\` to read another thread, or a \`cursor\` from an observation-group range.
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 — looking up source messages
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** — code, text, quotes, error messages, URLs, file paths, specific numbers
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 — even if you have no observations yet, their other threads may contain it` : ""}
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 — for example, to read one specific tool result or code block without loading every part.
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 — call recall cursor="..." partIndex=N detail="high" for full content]\`
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 — the chunks together contain the full part. Retrying without \`charOffset\` returns the same prefix again.
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: opts.recentMessages,
24783
+ get recentMessages() {
24784
+ return resolveRecentMessages();
24785
+ },
24775
24786
  mainAgent: opts.mainAgent,
24776
24787
  memory: opts.memory,
24777
24788
  sendSignal: opts.sendSignal,
@@ -25530,7 +25541,7 @@ const YEAR = String.raw`(?:19|20|21)\d{2}(?!\d)`;
25530
25541
  const MERIDIEM = String.raw`(?:[AaPp]\.[Mm]\.|[AaPp][Mm]\b)`;
25531
25542
  const TIME = String.raw`(?:,?\s+(?:at\s+)?\d{1,2}:\d{2}(?:\s*${MERIDIEM})?|\s+at\s+\d{1,2}\s*${MERIDIEM})`;
25532
25543
  const QUALIFIER = String.raw`(?:(?:early|mid|late)[- ](?:to[- ](?:early|mid|late)[- ])?)`;
25533
- const RANGE_SEP = String.raw`(?:\s*[–—]\s*|\s*-\s*|\s+(?:to|through|until)\s+)`;
25544
+ const RANGE_SEP = String.raw`(?:\s*[\u2013\u2014]\s*|\s*-\s*|\s+(?:to|through|until)\s+)`;
25534
25545
  /**
25535
25546
  * Dates written into observation text that carry their own year, longest forms first:
25536
25547
  * "Mar 1 - Mar 18, 2025", "May 27-28, 2023", "January 10, 2024 at 3:00 PM",
@@ -25833,15 +25844,15 @@ const SHORT_TOKEN_THRESHOLD = 3;
25833
25844
  const KANA_CHARS_PER_TOKEN = 1.35;
25834
25845
  const DEFAULT_LANGUAGE_CONFIGS = [
25835
25846
  {
25836
- pattern: /[äöüßẞ]/i,
25847
+ pattern: /[\u00E4\u00F6\u00FC\u00DF\u1E9E]/i,
25837
25848
  averageCharsPerToken: 2.6
25838
25849
  },
25839
25850
  {
25840
- pattern: /[éèêëàâîïôûùüÿçœæáíóúñ]/i,
25851
+ pattern: /[\u00E9\u00E8\u00EA\u00EB\u00E0\u00E2\u00EE\u00EF\u00F4\u00FB\u00F9\u00FC\u00FF\u00E7\u0153\u00E6\u00E1\u00ED\u00F3\u00FA\u00F1]/i,
25841
25852
  averageCharsPerToken: 3
25842
25853
  },
25843
25854
  {
25844
- pattern: /[ąćęłńóśźżěščřžýůúďťň]/i,
25855
+ pattern: /[\u0105\u0107\u0119\u0142\u0144\u00F3\u015B\u017A\u017C\u011B\u0161\u010D\u0159\u017E\u00FD\u016F\u00FA\u010F\u0165\u0148]/i,
25845
25856
  averageCharsPerToken: 2.5
25846
25857
  },
25847
25858
  {
@@ -25930,10 +25941,10 @@ function sanitizeSurrogates(value) {
25930
25941
  if (next >= 56320 && next <= 57343) {
25931
25942
  sanitized += value.charAt(index) + value.charAt(index + 1);
25932
25943
  index++;
25933
- } else sanitized += "�";
25944
+ } else sanitized += "\uFFFD";
25934
25945
  continue;
25935
25946
  }
25936
- sanitized += code >= 56320 && code <= 57343 ? "�" : value[index];
25947
+ sanitized += code >= 56320 && code <= 57343 ? "\uFFFD" : value[index];
25937
25948
  }
25938
25949
  return sanitized;
25939
25950
  }
@@ -25955,7 +25966,7 @@ function truncatePath(path) {
25955
25966
  const headLength = 50;
25956
25967
  const tailLength = 60;
25957
25968
  const omitted = path.length - headLength - tailLength;
25958
- return `${safeSlice(path, headLength)}…[${omitted} chars; ${stablePathDigest(path)}]…${safeTail(path, tailLength)}`;
25969
+ return `${safeSlice(path, headLength)}\u2026[${omitted} chars; ${stablePathDigest(path)}]\u2026${safeTail(path, tailLength)}`;
25959
25970
  }
25960
25971
  function formatPath(parent, key, isArray) {
25961
25972
  if (isArray) return truncatePath(`${parent}[${key}]`);
@@ -26064,7 +26075,7 @@ function selectOutlineEntries(entries, limits) {
26064
26075
  const rendered = joinEntries(selected, marker);
26065
26076
  if (fits(rendered, limits)) return rendered;
26066
26077
  if (fits(marker, limits)) return marker;
26067
- return fits("…", limits) ? "…" : "";
26078
+ return fits("\u2026", limits) ? "\u2026" : "";
26068
26079
  }
26069
26080
  function indentPreview(value) {
26070
26081
  return value.split("\n").map((line) => ` | ${line}`).join("\n");
@@ -26107,13 +26118,13 @@ function formatToolArgumentsForObserver(value, options) {
26107
26118
  if (!isObjectLike$1(value)) {
26108
26119
  if (typeof value !== "string" || value.length <= OBSERVER_TOOL_ARGUMENT_INLINE_STRING_MAX_CHARS) {
26109
26120
  const primitive = formatPrimitive(value);
26110
- return fits(primitive, limits) ? primitive : fits("…", limits) ? "…" : "";
26121
+ return fits(primitive, limits) ? primitive : fits("\u2026", limits) ? "\u2026" : "";
26111
26122
  }
26112
26123
  const summary = `<string, ${value.length} characters; preview size-limited>`;
26113
26124
  const rendered = appendWithinBudget(summary, formatPreview("preview", value, limits, summary), limits);
26114
26125
  if (rendered) return rendered;
26115
26126
  if (fits(summary, limits)) return summary;
26116
- return fits("…", limits) ? "…" : "";
26127
+ return fits("\u2026", limits) ? "\u2026" : "";
26117
26128
  }
26118
26129
  const outline = [];
26119
26130
  const previews = [];
@@ -26359,24 +26370,24 @@ function formatToolResultForObserver(value, options) {
26359
26370
  const OBSERVER_EXTRACTION_INSTRUCTIONS = `CRITICAL: DISTINGUISH USER ASSERTIONS FROM QUESTIONS
26360
26371
 
26361
26372
  When the user TELLS you something about themselves, mark it as an assertion:
26362
- - "I have two kids" → 🔴 (14:30) User stated has two kids
26363
- - "I work at Acme Corp" → 🔴 (14:31) User stated works at Acme Corp
26364
- - "I graduated in 2019" → 🔴 (14:32) User stated graduated in 2019
26373
+ - "I have two kids" \u2192 \u{1F534} (14:30) User stated has two kids
26374
+ - "I work at Acme Corp" \u2192 \u{1F534} (14:31) User stated works at Acme Corp
26375
+ - "I graduated in 2019" \u2192 \u{1F534} (14:32) User stated graduated in 2019
26365
26376
 
26366
26377
  When the user ASKS about something, mark it as a question/request:
26367
- - "Can you help me with X?" → 🔴 (15:00) User asked help with X
26368
- - "What's the best way to do Y?" → 🔴 (15:01) User asked best way to do Y
26378
+ - "Can you help me with X?" \u2192 \u{1F534} (15:00) User asked help with X
26379
+ - "What's the best way to do Y?" \u2192 \u{1F534} (15:01) User asked best way to do Y
26369
26380
 
26370
26381
  Distinguish between QUESTIONS and STATEMENTS OF INTENT:
26371
- - "Can you recommend..." → Question (extract as "User asked...")
26372
- - "I'm looking forward to [doing X]" → Statement of intent (extract as "User stated they will [do X] (include estimated/actual date if mentioned)")
26373
- - "I need to [do X]" → Statement of intent (extract as "User stated they need to [do X] (again, add date if mentioned)")
26382
+ - "Can you recommend..." \u2192 Question (extract as "User asked...")
26383
+ - "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)")
26384
+ - "I need to [do X]" \u2192 Statement of intent (extract as "User stated they need to [do X] (again, add date if mentioned)")
26374
26385
 
26375
26386
  STATE CHANGES AND UPDATES:
26376
26387
  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" → "User will start doing X (changing from Y)"
26378
- - "I'm switching from A to B" → "User is switching from A to B"
26379
- - "I moved my stuff to the new place" → "User moved their stuff to the new place (no longer at previous location)"
26388
+ - "I'm going to start doing X instead of Y" \u2192 "User will start doing X (changing from Y)"
26389
+ - "I'm switching from A to B" \u2192 "User is switching from A to B"
26390
+ - "I moved my stuff to the new place" \u2192 "User moved their stuff to the new place (no longer at previous location)"
26380
26391
 
26381
26392
  If the new state contradicts or updates previous information, make that explicit:
26382
26393
  - BAD: "User plans to use the new method"
@@ -26467,11 +26478,11 @@ BAD: User got something.
26467
26478
  GOOD: User purchased / received / was given something. (be specific)
26468
26479
 
26469
26480
  Common clarifications:
26470
- - "getting" something regularly → "subscribed to" or "enrolled in"
26471
- - "getting" something once → "purchased" or "acquired"
26472
- - "got" → "purchased", "received as gift", "was given", "picked up"
26473
- - "signed up" → "enrolled in", "registered for", "subscribed to"
26474
- - "stopped getting" → "canceled", "unsubscribed from", "discontinued"
26481
+ - "getting" something regularly \u2192 "subscribed to" or "enrolled in"
26482
+ - "getting" something once \u2192 "purchased" or "acquired"
26483
+ - "got" \u2192 "purchased", "received as gift", "was given", "picked up"
26484
+ - "signed up" \u2192 "enrolled in", "registered for", "subscribed to"
26485
+ - "stopped getting" \u2192 "canceled", "unsubscribed from", "discontinued"
26475
26486
 
26476
26487
  When the assistant interprets or confirms the user's vague language, prefer the assistant's precise terminology.
26477
26488
 
@@ -26556,16 +26567,16 @@ AVOIDING REPETITIVE OBSERVATIONS:
26556
26567
  - Do NOT repeat the same observation across multiple turns if there is no new information.
26557
26568
  - 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
26569
 
26559
- Example — BAD (repetitive):
26560
- * 🟡 (14:30) Agent used view tool on src/auth.ts
26561
- * 🟡 (14:31) Agent used view tool on src/users.ts
26562
- * 🟡 (14:32) Agent used view tool on src/routes.ts
26570
+ Example \u2014 BAD (repetitive):
26571
+ * \u{1F7E1} (14:30) Agent used view tool on src/auth.ts
26572
+ * \u{1F7E1} (14:31) Agent used view tool on src/users.ts
26573
+ * \u{1F7E1} (14:32) Agent used view tool on src/routes.ts
26563
26574
 
26564
- Example — GOOD (grouped):
26565
- * 🟡 (14:30) Agent browsed source files for auth flow
26566
- * -> viewed src/auth.ts — found token validation logic
26567
- * -> viewed src/users.ts — found user lookup by email
26568
- * -> viewed src/routes.ts — found middleware chain
26575
+ Example \u2014 GOOD (grouped):
26576
+ * \u{1F7E1} (14:30) Agent browsed source files for auth flow
26577
+ * -> viewed src/auth.ts \u2014 found token validation logic
26578
+ * -> viewed src/users.ts \u2014 found user lookup by email
26579
+ * -> viewed src/routes.ts \u2014 found middleware chain
26569
26580
 
26570
26581
  Only add a new observation for a repeated action if the NEW result changes the picture.
26571
26582
 
@@ -26578,29 +26589,29 @@ COMPLETION TRACKING:
26578
26589
  Completion observations are not just summaries. They are explicit memory signals to the assistant that a task, question, or subtask has been resolved.
26579
26590
  Without clear completion markers, the assistant may forget that work is already finished and may repeat, reopen, or continue an already-completed task.
26580
26591
 
26581
- Use ✅ to answer: "What exactly is now done?"
26592
+ Use \u2705 to answer: "What exactly is now done?"
26582
26593
  Choose completion observations that help the assistant know what is finished and should not be reworked unless new information appears.
26583
26594
 
26584
- Use ✅ when:
26595
+ Use \u2705 when:
26585
26596
  - The user explicitly confirms something worked or was answered ("thanks, that fixed it", "got it", "perfect")
26586
26597
  - The assistant provided a definitive, complete answer to a factual question and the user moved on
26587
26598
  - A multi-step task reached its stated goal
26588
26599
  - The user acknowledged receipt of requested information
26589
26600
  - A concrete subtask, fix, deliverable, or implementation step became complete during ongoing work
26590
26601
 
26591
- Do NOT use ✅ when:
26592
- - The assistant merely responded — the user might follow up with corrections
26602
+ Do NOT use \u2705 when:
26603
+ - The assistant merely responded \u2014 the user might follow up with corrections
26593
26604
  - The topic is paused but not resolved ("I'll try that later")
26594
26605
  - The user's reaction is ambiguous
26595
26606
 
26596
26607
  FORMAT:
26597
26608
  As a sub-bullet under the related observation group:
26598
- * 🔴 (14:30) User asked how to configure auth middleware
26609
+ * \u{1F534} (14:30) User asked how to configure auth middleware
26599
26610
  * -> Agent explained JWT setup with code example
26600
- * ✅ User confirmed auth is working
26611
+ * \u2705 User confirmed auth is working
26601
26612
 
26602
26613
  Or as a standalone observation when closing out a broader task:
26603
- * ✅ (14:45) Auth configuration task completed — user confirmed middleware is working
26614
+ * \u2705 (14:45) Auth configuration task completed \u2014 user confirmed middleware is working
26604
26615
 
26605
26616
  Completion observations should be terse but specific about WHAT was completed.
26606
26617
  Prefer concrete resolved outcomes over abstract workflow status so the assistant remembers what is already done.`;
@@ -26617,28 +26628,28 @@ buildObserverOutputFormat();
26617
26628
  */
26618
26629
  function buildObserverOutputFormat(extractors) {
26619
26630
  return `Use priority levels:
26620
- - 🔴 High: explicit user facts, preferences, unresolved goals, critical context
26621
- - 🟡 Medium: project details, learned information, tool results
26622
- - 🟢 Low: minor details, uncertain observations
26623
- - ✅ Completed: concrete task finished, question answered, issue resolved, goal achieved, or subtask completed in a way that helps the assistant know it is done
26631
+ - \u{1F534} High: explicit user facts, preferences, unresolved goals, critical context
26632
+ - \u{1F7E1} Medium: project details, learned information, tool results
26633
+ - \u{1F7E2} Low: minor details, uncertain observations
26634
+ - \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
26635
 
26625
26636
  Group related observations (like tool sequences) by indenting:
26626
- * 🔴 (14:33) Agent debugging auth issue
26637
+ * \u{1F534} (14:33) Agent debugging auth issue
26627
26638
  * -> ran git status, found 3 modified files
26628
26639
  * -> viewed auth.ts:45-60, found missing null check
26629
26640
  * -> applied fix, tests now pass
26630
- * ✅ Tests passing, auth issue resolved
26641
+ * \u2705 Tests passing, auth issue resolved
26631
26642
 
26632
26643
  Group observations by date. Within a date, list observations in the order the events happened (not by importance), each with 24-hour time.
26633
26644
 
26634
26645
  <observations>
26635
26646
  Date: Dec 4, 2025
26636
- * 🔴 (14:30) User prefers direct answers
26637
- * 🔴 (14:31) Working on feature X
26638
- * 🟡 (14:32) User might prefer dark mode
26647
+ * \u{1F534} (14:30) User prefers direct answers
26648
+ * \u{1F534} (14:31) Working on feature X
26649
+ * \u{1F7E1} (14:32) User might prefer dark mode
26639
26650
 
26640
26651
  Date: Dec 5, 2025
26641
- * 🔴 (09:15) Continued work on feature X
26652
+ * \u{1F534} (09:15) Continued work on feature X
26642
26653
  </observations>
26643
26654
 
26644
26655
  ${buildExtractorOutputSections(extractors ?? []) || (extractors === void 0 ? `
@@ -26668,9 +26679,9 @@ const OBSERVER_GUIDELINES = `- Be specific enough for the assistant to act on
26668
26679
  - If the agent calls tools, observe what was called, why, and what was learned
26669
26680
  - When observing files with line numbers, include the line number if useful
26670
26681
  - 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 (🔴, 🟡, 🟢) or a completion marker (✅)
26672
- - Capture the user's words closely — short/medium messages near-verbatim, long messages summarized with key quotes. User confirmations or explicit resolved outcomes should be ✅ when they clearly signal something is done; unresolved or critical user facts remain 🔴
26673
- - Treat ✅ as a memory signal that tells the assistant something is finished and should not be repeated unless new information changes it
26682
+ - Make sure you start each observation with a priority emoji (\u{1F534}, \u{1F7E1}, \u{1F7E2}) or a completion marker (\u2705)
26683
+ - 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}
26684
+ - Treat \u2705 as a memory signal that tells the assistant something is finished and should not be repeated unless new information changes it
26674
26685
  - Make completion observations answer "What exactly is now done?"
26675
26686
  - Prefer concrete resolved outcomes over meta-level workflow or bookkeeping updates
26676
26687
  - When multiple concrete things were completed, capture the concrete completed work rather than collapsing it into a vague progress summary
@@ -26724,8 +26735,8 @@ For multi-thread output, wrap each thread's observations like this:
26724
26735
  <observations>
26725
26736
  <thread id="thread_id_1">
26726
26737
  Date: Dec 4, 2025
26727
- * 🔴 (14:30) User prefers direct answers
26728
- * 🔴 (14:31) Working on feature X${currentTaskEnabled ? `
26738
+ * \u{1F534} (14:30) User prefers direct answers
26739
+ * \u{1F534} (14:31) Working on feature X${currentTaskEnabled ? `
26729
26740
 
26730
26741
  <current-task>
26731
26742
  What the agent is currently working on in this thread
@@ -26738,7 +26749,7 @@ Hint for the agent's next message in this thread
26738
26749
 
26739
26750
  <thread id="thread_id_2">
26740
26751
  Date: Dec 5, 2025
26741
- * 🔴 (09:15) User asked about deployment${currentTaskEnabled ? `
26752
+ * \u{1F534} (09:15) User asked about deployment${currentTaskEnabled ? `
26742
26753
 
26743
26754
  <current-task>
26744
26755
  Current task for this thread
@@ -27586,7 +27597,7 @@ function sanitizeObservationLines(observations) {
27586
27597
  const lines = observations.split("\n");
27587
27598
  let changed = false;
27588
27599
  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) + " … [truncated]";
27600
+ lines[i] = safeSlice(lines[i], MAX_OBSERVATION_LINE_CHARS) + " \u2026 [truncated]";
27590
27601
  changed = true;
27591
27602
  }
27592
27603
  return changed ? lines.join("\n") : observations;
@@ -27810,8 +27821,8 @@ function extractCurrentTask(observations) {
27810
27821
  */
27811
27822
  function optimizeObservationsForContext(observations) {
27812
27823
  let optimized = stripEphemeralAnchorIds(observations);
27813
- optimized = optimized.replace(/🟡\s*/g, "");
27814
- optimized = optimized.replace(/🟢\s*/g, "");
27824
+ optimized = optimized.replace(/\uD83D\uDFE1\s*/g, "");
27825
+ optimized = optimized.replace(/\uD83D\uDFE2\s*/g, "");
27815
27826
  optimized = optimized.replace(/\s*->\s*/g, " ");
27816
27827
  optimized = optimized.replace(/ +/g, " ");
27817
27828
  optimized = optimized.replace(/\n{3,}/g, "\n\n");
@@ -30097,8 +30108,8 @@ const updateWorkingMemoryTool = (memoryConfig) => {
30097
30108
  }
30098
30109
  const usesMergeSemantics = Boolean(schema);
30099
30110
  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 — 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.`;
30101
- const description = schema ? useStateSignals ? `${stateSignalsPreamble} Data is merged with existing memory — only include fields you want to add or update.` : `Update the working memory with new information. Data is merged with existing memory - only include fields you want to add or update. To preserve existing data, omit the field entirely. Arrays are replaced entirely when provided, so pass the complete array or omit it to keep the existing values.` : useStateSignals ? `${stateSignalsPreamble} Pass the full updated Markdown blob as a string in the memory field.` : `Update the working memory with new information. Any data not included will be overwritten. Always pass data as string to the memory field. Never pass an object.`;
30111
+ 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.`;
30112
+ 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
30113
  return createTool({
30103
30114
  id: "update-working-memory",
30104
30115
  description,
@@ -31129,8 +31140,8 @@ async function pageGroups({ om, threadId, resourceId, groupId, recordId, directi
31129
31140
  })).count > 0;
31130
31141
  const hasLater = direction === "before" || hasMore;
31131
31142
  const newer = hasLater ? null : await newerMessagesNote(page.at(-1).group, countNewerMessages, pagingThreadId);
31132
- text.unshift(hasEarlier ? `— Browse earlier: ${pagingCall(page[0].group.id, "before", pagingThreadId, page[0].record.id)} —` : "— Start of retained observation history for this thread. —");
31133
- text.push(hasLater ? `— Browse later: ${pagingCall(page.at(-1).group.id, "after", pagingThreadId, page.at(-1).record.id)} —` : newer ? `— End of observation history for this thread. ${newer} —` : "— End of retained observation history for this thread. —");
31143
+ 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");
31144
+ 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
31145
  text.unshift(`### Observation page\nThread: ${threadTitle || "(untitled)"}\nShowing ${page.length} groups ${requestedDirection === void 0 ? "starting at" : `strictly ${direction}`} \`${groupId}\` (oldest first).`);
31135
31146
  return {
31136
31147
  results: text.join("\n\n"),
@@ -31318,7 +31329,7 @@ async function listThreadsForResource({ memory, resourceId, currentThreadId, pag
31318
31329
  const title = thread.title || "(untitled)";
31319
31330
  const updated = formatTimestamp(thread.updatedAt);
31320
31331
  const created = formatTimestamp(thread.createdAt);
31321
- const marker = isCurrent ? " ← current" : "";
31332
+ const marker = isCurrent ? " \u2190 current" : "";
31322
31333
  lines.push(`- **${title}**${marker}`);
31323
31334
  lines.push(` id: ${thread.id}`);
31324
31335
  lines.push(` updated: ${updated} | created: ${created}`);
@@ -31497,7 +31508,7 @@ async function searchMessagesForResource({ memory, om, resourceId, currentThread
31497
31508
  const groupLine = match.groupId ? `- observation group: ${groupCursor(match.groupId, match.recordId)}` : void 0;
31498
31509
  const scoreLine = `- score: ${match.score.toFixed(2)}`;
31499
31510
  const prev = i > 0 ? ordered[i - 1].match : void 0;
31500
- if (om && prev?.groupId && match.groupId && prev.threadId === match.threadId) sections.push(`— Observation groups may be hidden between these results; continue with ${pagingCall(prev.groupId, "after", includeThreadId ? prev.threadId : void 0, prev.recordId)} —`);
31511
+ 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
31512
  if (suppression) {
31502
31513
  sections.push(`${groupLine}\n thread: ${match.threadId}; ${suppression}`);
31503
31514
  continue;
@@ -32052,7 +32063,7 @@ async function recallAttachmentView({ memory, threadId, resourceId, cursor, part
32052
32063
  const partType = rawPart?.type;
32053
32064
  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
32065
  const resolvedAttachment = resolveViewableAttachment(rawPart);
32055
- if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)} — ${resolvedAttachment.note}` };
32066
+ if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)} \u2014 ${resolvedAttachment.note}` };
32056
32067
  return { content: [{
32057
32068
  type: "text",
32058
32069
  text: formatAttachmentPart(partType, rawPart)
@@ -32455,7 +32466,7 @@ const recallTool = (_memoryConfig, options) => {
32455
32466
  if (!thread) return { error: "Could not resolve current thread." };
32456
32467
  if (isResourceScope && resourceId && thread.resourceId !== resourceId) throw new Error("Thread does not belong to the active resource");
32457
32468
  return {
32458
- threads: `- **${thread.title || "(untitled)"}** ← current\n id: ${thread.id}\n updated: ${formatTimestamp(thread.updatedAt)} | created: ${formatTimestamp(thread.createdAt)}`,
32469
+ threads: `- **${thread.title || "(untitled)"}** \u2190 current\n id: ${thread.id}\n updated: ${formatTimestamp(thread.updatedAt)} | created: ${formatTimestamp(thread.createdAt)}`,
32459
32470
  count: 1,
32460
32471
  page: 0,
32461
32472
  hasMore: false
@@ -33215,9 +33226,9 @@ const suggestedResponseInstructions = `Hint for the agent's immediate next messa
33215
33226
  - "The assistant should wait for the user to respond before continuing."
33216
33227
  - Call the view tool on src/example.ts to continue debugging.`;
33217
33228
  const threadTitleInstructions = `A short, noun-phrase title for this conversation (2-5 words). Examples:
33218
- - "Auth bug fix" — not "Fixing the auth bug"
33219
- - "Dark mode toggle" — not "User wants dark mode toggle added"
33220
- - "Deployment pipeline setup" — not "Setting up deployment pipeline for project"
33229
+ - "Auth bug fix" \u2014 not "Fixing the auth bug"
33230
+ - "Dark mode toggle" \u2014 not "User wants dark mode toggle added"
33231
+ - "Deployment pipeline setup" \u2014 not "Setting up deployment pipeline for project"
33221
33232
  Only update when the topic meaningfully changes.`;
33222
33233
  function createCurrentTaskExtractor() {
33223
33234
  return new Extractor({
@@ -34294,7 +34305,7 @@ var SyncObservationStrategy = class extends ObservationStrategy {
34294
34305
  failures: result.extractionFailures,
34295
34306
  previousValues: this.priorExtractedValues,
34296
34307
  rawObservations: result.observations,
34297
- recentMessages: formatMessagesForObserver(this.opts.messages, {
34308
+ recentMessages: () => formatMessagesForObserver(this.opts.messages, {
34298
34309
  maxPartLength: 500,
34299
34310
  timeZone: this.opts.record.observedTimezone
34300
34311
  }),
@@ -34519,7 +34530,7 @@ var AsyncBufferObservationStrategy = class extends ObservationStrategy {
34519
34530
  failures: result.extractionFailures,
34520
34531
  previousValues: this.priorExtractedValues,
34521
34532
  rawObservations: result.observations,
34522
- recentMessages: formatMessagesForObserver(messages, {
34533
+ recentMessages: () => formatMessagesForObserver(messages, {
34523
34534
  maxPartLength: 500,
34524
34535
  timeZone: this.opts.record.observedTimezone
34525
34536
  }),
@@ -34949,7 +34960,7 @@ var ResourceScopedObservationStrategy = class extends ObservationStrategy {
34949
34960
  failures: result.extractionFailures,
34950
34961
  previousValues,
34951
34962
  rawObservations: result.observations,
34952
- recentMessages: formatMessagesForObserver(threadMessages, {
34963
+ recentMessages: () => formatMessagesForObserver(threadMessages, {
34953
34964
  maxPartLength: 500,
34954
34965
  timeZone: this.opts.record.observedTimezone
34955
34966
  }),
@@ -35282,7 +35293,7 @@ var ObservationStep = class {
35282
35293
  }
35283
35294
  /** Step context from prepare(). Throws if prepare() hasn't been called. */
35284
35295
  get context() {
35285
- if (!this._context) throw new Error("Step not prepared yet — call prepare() first");
35296
+ if (!this._context) throw new Error("Step not prepared yet \u2014 call prepare() first");
35286
35297
  return this._context;
35287
35298
  }
35288
35299
  /**
@@ -35702,7 +35713,7 @@ var ObservationStep = class {
35702
35713
  const messagesToSeal = messageToSeal ? [messageToSeal] : [];
35703
35714
  this.turn.abortSignal?.throwIfAborted();
35704
35715
  om.sealMessagesForBuffering(messagesToSeal);
35705
- if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation — step-0 seeded response message holds the active id");
35716
+ if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation \u2014 step-0 seeded response message holds the active id");
35706
35717
  else try {
35707
35718
  await this.turn.hooks?.onSyncObservationComplete?.();
35708
35719
  } catch (error) {
@@ -35853,12 +35864,12 @@ var ObservationTurn = class {
35853
35864
  messageList;
35854
35865
  /** The current cached record. Refreshed after mutations (activate/observe/reflect). */
35855
35866
  get record() {
35856
- if (!this._record) throw new Error("Turn not started — call start() first");
35867
+ if (!this._record) throw new Error("Turn not started \u2014 call start() first");
35857
35868
  return this._record;
35858
35869
  }
35859
35870
  /** The context loaded during start(). */
35860
35871
  get context() {
35861
- if (!this._context) throw new Error("Turn not started — call start() first");
35872
+ if (!this._context) throw new Error("Turn not started \u2014 call start() first");
35862
35873
  return this._context;
35863
35874
  }
35864
35875
  /** Whether the turn has been ended and can no longer accept steps. */
@@ -35927,7 +35938,7 @@ var ObservationTurn = class {
35927
35938
  * (its output messages will be saved at the start of the new step's prepare()).
35928
35939
  */
35929
35940
  step(stepNumber) {
35930
- if (!this._started) throw new Error("Turn not started — call start() first");
35941
+ if (!this._started) throw new Error("Turn not started \u2014 call start() first");
35931
35942
  if (this._ended) throw new Error("Turn already ended");
35932
35943
  this._currentStep = new ObservationStep(this, stepNumber);
35933
35944
  return this._currentStep;
@@ -36150,8 +36161,8 @@ When consolidating observations:
36150
36161
  - 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
36162
  - Prefer many short factual lines over prose summaries. Do not replace facts with generalities like "discussed travel plans"
36152
36163
  - Combine related items where it makes sense (e.g., "agent called view tool 5 times on file x")
36153
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36154
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
36164
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36165
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
36155
36166
  - Condense the wording of older observations more than recent ones, but keep their facts
36156
36167
 
36157
36168
  CRITICAL: USER ASSERTIONS vs QUESTIONS
@@ -36173,23 +36184,23 @@ When observations contain <thread id="..."> sections:
36173
36184
  Example input:
36174
36185
  <thread id="thread-1">
36175
36186
  Date: Dec 4, 2025
36176
- * 🔴 (14:30) User prefers TypeScript
36177
- * 🟡 (14:35) Working on auth feature
36187
+ * \u{1F534} (14:30) User prefers TypeScript
36188
+ * \u{1F7E1} (14:35) Working on auth feature
36178
36189
  </thread>
36179
36190
  <thread id="thread-2">
36180
36191
  Date: Dec 4, 2025
36181
- * 🔴 (15:00) User prefers TypeScript
36182
- * 🟡 (15:05) Debugging API endpoint
36192
+ * \u{1F534} (15:00) User prefers TypeScript
36193
+ * \u{1F7E1} (15:05) Debugging API endpoint
36183
36194
  </thread>
36184
36195
 
36185
36196
  Example output (consolidated):
36186
36197
  Date: Dec 4, 2025
36187
- * 🔴 (14:30) User prefers TypeScript
36198
+ * \u{1F534} (14:30) User prefers TypeScript
36188
36199
  <thread id="thread-1">
36189
- * 🟡 (14:35) Working on auth feature
36200
+ * \u{1F7E1} (14:35) Working on auth feature
36190
36201
  </thread>
36191
36202
  <thread id="thread-2">
36192
- * 🟡 (15:05) Debugging API endpoint
36203
+ * \u{1F7E1} (15:05) Debugging API endpoint
36193
36204
  </thread>
36194
36205
 
36195
36206
  === OUTPUT FORMAT ===
@@ -36220,8 +36231,8 @@ Please re-process with slightly more compression:
36220
36231
  - Memory is getting long - use a more condensed style throughout
36221
36232
  - Combine related items more aggressively but do not lose important specific details of names, places, events, and people
36222
36233
  - 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 ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36224
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
36234
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36235
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
36225
36236
 
36226
36237
  Aim for a 8/10 detail level.
36227
36238
  `,
@@ -36237,8 +36248,8 @@ Please re-process with much more aggressive compression:
36237
36248
  - Combine related items aggressively but do not lose important specific details of names, places, events, and people
36238
36249
  - 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
36250
  - If the same file or module is mentioned across many observations, merge into one entry covering the full arc
36240
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36241
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
36251
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36252
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
36242
36253
  - Remove redundant information and merge overlapping observations
36243
36254
 
36244
36255
  Aim for a 6/10 detail level.
@@ -36249,14 +36260,14 @@ Aim for a 6/10 detail level.
36249
36260
  Your previous reflections have failed to compress sufficiently after multiple attempts.
36250
36261
 
36251
36262
  Please re-process with maximum compression:
36252
- - Summarize the oldest observations (first 50-70%) into brief high-level paragraphs — only key facts, decisions, and outcomes
36263
+ - Summarize the oldest observations (first 50-70%) into brief high-level paragraphs \u2014 only key facts, decisions, and outcomes
36253
36264
  - For the most recent observations (last 30-50%), retain important details but still use a condensed style
36254
- - Ruthlessly merge related observations — if 10 observations are about the same topic, combine into 1-2 lines
36255
- - Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries — drop individual steps entirely
36256
- - Drop procedural details (tool calls, retries, intermediate steps) — keep only final outcomes
36265
+ - Ruthlessly merge related observations \u2014 if 10 observations are about the same topic, combine into 1-2 lines
36266
+ - Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries \u2014 drop individual steps entirely
36267
+ - Drop procedural details (tool calls, retries, intermediate steps) \u2014 keep only final outcomes
36257
36268
  - Drop observations that are no longer relevant or have been superseded by newer information
36258
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36259
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
36269
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
36270
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
36260
36271
  - Preserve: names, dates, decisions, errors, user preferences, and architectural choices
36261
36272
 
36262
36273
  Aim for a 4/10 detail level.
@@ -36267,14 +36278,14 @@ Aim for a 4/10 detail level.
36267
36278
  Multiple compression attempts have failed. The content may already be dense from a prior reflection.
36268
36279
 
36269
36280
  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 — 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")
36271
- - Never preserve individual tool calls (viewed file X, searched for Y, ran build) — only preserve what was discovered or accomplished
36281
+ - 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")
36282
+ - Never preserve individual tool calls (viewed file X, searched for Y, ran build) \u2014 only preserve what was discovered or accomplished
36272
36283
  - Consolidate many related observations into single, more generic observations
36273
36284
  - Merge all same-day date groups into at most 2-3 date groups per day
36274
36285
  - For older content, each topic or task should be at most 1-2 observations capturing the key outcome
36275
36286
  - For recent content, retain more detail but still merge related items aggressively
36276
36287
  - If multiple observations describe incremental progress on the same task, keep only the final state
36277
- - Preserve ✅ completion markers and their outcomes but merge related completions into fewer lines
36288
+ - Preserve \u2705 completion markers and their outcomes but merge related completions into fewer lines
36278
36289
  - Preserve: user preferences, key decisions, architectural choices, and unresolved issues
36279
36290
 
36280
36291
  Aim for a 2/10 detail level. Fewer, more generic observations are better than many specific ones that exceed the budget.
@@ -36698,7 +36709,7 @@ var ReflectorRunner = class {
36698
36709
  operationType: "reflection",
36699
36710
  startedAt: streamContext.startedAt,
36700
36711
  tokensAttempted: originalTokens,
36701
- error: `Did not compress below threshold (${originalTokens} → ${reflectedTokens}, target: ${targetThreshold}), retrying at level ${currentLevel + 1}`,
36712
+ error: `Did not compress below threshold (${originalTokens} \u2192 ${reflectedTokens}, target: ${targetThreshold}), retrying at level ${currentLevel + 1}`,
36702
36713
  retrying: true,
36703
36714
  recordId: streamContext.recordId,
36704
36715
  threadId: streamContext.threadId
@@ -36728,7 +36739,7 @@ var ReflectorRunner = class {
36728
36739
  }
36729
36740
  currentLevel = Math.min(currentLevel + 1, maxLevel);
36730
36741
  }
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)" : ""} — refusing to commit an empty reflection over ${originalTokens} observation tokens`);
36742
+ 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
36743
  const structuredExtraction = await extractStructuredValues({
36733
36744
  agent,
36734
36745
  source: "reflector",
@@ -36869,7 +36880,7 @@ var ReflectorRunner = class {
36869
36880
  const reflectedObservationLineCount = linesToReflect;
36870
36881
  const sliceTokenEstimate = Math.round(avgTokensPerLine * linesToReflect);
36871
36882
  const compressionTarget = Math.round(sliceTokenEstimate * .75);
36872
- omDebug(`[OM:reflect] doAsyncBufferedReflection: slicing observations for reflection — totalLines=${totalLines}, avgTokPerLine=${avgTokensPerLine.toFixed(1)}, activationPointTokens=${activationPointTokens}, linesToReflect=${linesToReflect}/${totalLines}, sliceTokenEstimate=${sliceTokenEstimate}, compressionTarget=${compressionTarget}`);
36883
+ 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
36884
  omDebug(`[OM:reflect] doAsyncBufferedReflection: starting reflector call, recordId=${currentRecord.id}, observationTokens=${sliceTokenEstimate}, compressionTarget=${compressionTarget} (inputTokens), activeObsLength=${activeObservations.length}, reflectedLineCount=${reflectedObservationLineCount}`);
36874
36885
  if (writer) {
36875
36886
  const startMarker = createBufferingStartMarker({
@@ -37041,7 +37052,7 @@ var ReflectorRunner = class {
37041
37052
  const unreflectedTailTokens = unreflectedContent ? this.tokenCounter.countObservations(unreflectedContent) : 0;
37042
37053
  const bufferedReflectionTokens = freshRecord.bufferedReflectionTokens ?? 0;
37043
37054
  if (unreflectedTailTokens < bufferedReflectionTokens) {
37044
- omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation — unreflectedTailTokens=${unreflectedTailTokens} < bufferedReflectionTokens=${bufferedReflectionTokens}; keeping buffer for threshold activation`);
37055
+ omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation \u2014 unreflectedTailTokens=${unreflectedTailTokens} < bufferedReflectionTokens=${bufferedReflectionTokens}; keeping buffer for threshold activation`);
37045
37056
  return {
37046
37057
  status: "suppressed",
37047
37058
  reason: "composition"
@@ -37052,7 +37063,7 @@ var ReflectorRunner = class {
37052
37063
  const regularActivationTarget = reflectThreshold * (1 - bufferActivation);
37053
37064
  const minCombinedTokens = Math.round(regularActivationTarget * EARLY_ACTIVATION_SIZE_FLOOR_RATIO);
37054
37065
  if (combinedTokenCount < minCombinedTokens) {
37055
- omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation — combinedTokenCount=${combinedTokenCount} < minCombinedTokens=${minCombinedTokens} (${EARLY_ACTIVATION_SIZE_FLOOR_RATIO * 100}% of regular activation target ${Math.round(regularActivationTarget)}, threshold=${reflectThreshold}, bufferActivation=${bufferActivation}); keeping buffer for threshold activation`);
37066
+ 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
37067
  return {
37057
37068
  status: "suppressed",
37058
37069
  reason: "size"
@@ -37181,7 +37192,7 @@ var ReflectorRunner = class {
37181
37192
  omDebug(`[OM:reflect] isReflecting=true and active in this process, skipping`);
37182
37193
  return;
37183
37194
  }
37184
- omDebug(`[OM:reflect] isReflecting=true but NOT active in this process — stale flag from dead process, clearing`);
37195
+ omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
37185
37196
  await this.storage.setReflectingFlag(record.id, false);
37186
37197
  }
37187
37198
  if (this.buffering.isAsyncReflectionEnabled()) {
@@ -37195,15 +37206,15 @@ var ReflectorRunner = class {
37195
37206
  else {
37196
37207
  const activationPoint = reflectThreshold * this.reflectionConfig.bufferActivation;
37197
37208
  if (observationTokens < activationPoint) {
37198
- omDebug(`[OM:reflect] skipping async reflection — observationTokens (${observationTokens}) below activation point (${activationPoint}), triggered by ${activationTriggeredBy}`);
37209
+ omDebug(`[OM:reflect] skipping async reflection \u2014 observationTokens (${observationTokens}) below activation point (${activationPoint}), triggered by ${activationTriggeredBy}`);
37199
37210
  return;
37200
37211
  }
37201
37212
  const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
37202
37213
  if (this.buffering.isAsyncBufferingInProgress(bufferKey) || BufferingCoordinator.lastBufferedBoundary.has(bufferKey)) {
37203
- omDebug(`[OM:reflect] skipping async reflection — reflection buffer already active or present for ${bufferKey}`);
37214
+ omDebug(`[OM:reflect] skipping async reflection \u2014 reflection buffer already active or present for ${bufferKey}`);
37204
37215
  return;
37205
37216
  }
37206
- omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) — starting background reflection`);
37217
+ omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) \u2014 starting background reflection`);
37207
37218
  this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
37208
37219
  return;
37209
37220
  }
@@ -37211,7 +37222,7 @@ var ReflectorRunner = class {
37211
37222
  if (activationTriggeredBy === "threshold") {
37212
37223
  const suppressedAtTokens = this.syncReflectionSuppression.get(lockKey);
37213
37224
  if (suppressedAtTokens !== void 0 && observationTokens === suppressedAtTokens) {
37214
- omDebug(`[OM:reflect] skipping sync reflection — observations unchanged at ${observationTokens} tokens since the last unproductive attempt; retrying once they change`);
37225
+ omDebug(`[OM:reflect] skipping sync reflection \u2014 observations unchanged at ${observationTokens} tokens since the last unproductive attempt; retrying once they change`);
37215
37226
  return;
37216
37227
  }
37217
37228
  }
@@ -38054,7 +38065,7 @@ var ObservationalMemory = class ObservationalMemory {
38054
38065
  const asyncBufferingDisabled = config.observation?.bufferTokens === false || config.scope === "resource" && !userExplicitlyConfiguredAsync;
38055
38066
  if (isSharedBudget && !asyncBufferingDisabled) {
38056
38067
  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 — this opt-out is only needed when using shareTokenBudget.");
38068
+ 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
38069
  }
38059
38070
  const observationActivateAfterIdle = config.observation?.activateAfterIdle ?? config.activateAfterIdle;
38060
38071
  const observationActivateAfterIdlePath = config.observation?.activateAfterIdle !== void 0 ? "observation.activateAfterIdle" : "activateAfterIdle";
@@ -38151,7 +38162,7 @@ var ObservationalMemory = class ObservationalMemory {
38151
38162
  hasWarnedResourceScopeDeprecation = true;
38152
38163
  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
38164
  }
38154
- omDebug(`[OM:init] new ObservationalMemory instance created — scope=${this.scope}, messageTokens=${JSON.stringify(this.observationConfig.messageTokens)}, obsAsyncEnabled=${this.buffering.isAsyncObservationEnabled()}, bufferTokens=${this.observationConfig.bufferTokens}, bufferActivation=${this.observationConfig.bufferActivation}, blockAfter=${this.observationConfig.blockAfter}, reflectionTokens=${this.reflectionConfig.observationTokens}, refAsyncEnabled=${this.buffering.isAsyncReflectionEnabled()}, refAsyncActivation=${this.reflectionConfig.bufferActivation}, refBlockAfter=${this.reflectionConfig.blockAfter}`);
38165
+ 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
38166
  }
38156
38167
  __registerMastra(mastra) {
38157
38168
  this.mastra = mastra;
@@ -38432,7 +38443,7 @@ var ObservationalMemory = class ObservationalMemory {
38432
38443
  threadId: null,
38433
38444
  resourceId: resourceId ?? threadId
38434
38445
  };
38435
- if (!threadId) throw new Error("ObservationalMemory (scope: 'thread') requires a threadId, but received an empty value. This is a bug — getThreadContext should have caught this earlier.");
38446
+ 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
38447
  return {
38437
38448
  threadId,
38438
38449
  resourceId: resourceId ?? threadId
@@ -38743,7 +38754,7 @@ var ObservationalMemory = class ObservationalMemory {
38743
38754
  const isImportant = new Array(totalCount);
38744
38755
  for (let i = 0; i < totalCount; i++) {
38745
38756
  lineTokens[i] = this.tokenCounter.countString(lines[i]);
38746
- isImportant[i] = lines[i].includes("🔴") || lines[i].includes("✅");
38757
+ isImportant[i] = lines[i].includes("\u{1F534}") || lines[i].includes("\u2705");
38747
38758
  }
38748
38759
  const suffixTokens = new Array(totalCount + 1);
38749
38760
  suffixTokens[totalCount] = 0;
@@ -39076,7 +39087,7 @@ ${formattedMessages}
39076
39087
  resourceId: freshRecord.resourceId ?? void 0
39077
39088
  });
39078
39089
  } catch (err) {
39079
- omError("[OM] Failed to persist sealed messages before buffering — skipping observation cycle", err);
39090
+ omError("[OM] Failed to persist sealed messages before buffering \u2014 skipping observation cycle", err);
39080
39091
  return;
39081
39092
  }
39082
39093
  const cycleId = `buffer-obs-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
@@ -40226,7 +40237,7 @@ ${formattedMessages}
40226
40237
  usage: void 0
40227
40238
  };
40228
40239
  }
40229
- omDebug(`[OM:reflect] isReflecting=true but NOT active in this process — stale flag from dead process, clearing`);
40240
+ omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
40230
40241
  await this.storage.setReflectingFlag(record.id, false);
40231
40242
  }
40232
40243
  await this.storage.setReflectingFlag(record.id, true);
@@ -40461,7 +40472,7 @@ ${formattedMessages}
40461
40472
  // src/processors/observational-memory/temporal-markers.ts
40462
40473
  const TEMPORAL_GAP_REMINDER_TYPE = "temporal-gap";
40463
40474
  function getTemporalGapReminderText(gapText, timestamp) {
40464
- return `${gapText} — ${formatTemporalTimestamp(new Date(timestamp))}`;
40475
+ return `${gapText} \u2014 ${formatTemporalTimestamp(new Date(timestamp))}`;
40465
40476
  }
40466
40477
  function getTemporalGapReminderMetadata(message, gapText, gapMs, timestamp) {
40467
40478
  const formattedTimestamp = formatTemporalTimestamp(new Date(timestamp));
@@ -40683,14 +40694,14 @@ var ObservationalMemoryProcessor = class {
40683
40694
  omDebug(`[OM:processInputStep:ENTER] step=${stepNumber}, hasMastraMemory=${!!requestContext?.get("MastraMemory")}, hasMemoryInfo=${!!messageList?.serialize()?.memoryInfo?.threadId}`);
40684
40695
  const context = this.engine.getThreadContext(requestContext, messageList);
40685
40696
  if (!context) {
40686
- omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null — returning early`);
40697
+ omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null \u2014 returning early`);
40687
40698
  return messageList;
40688
40699
  }
40689
40700
  const gatewayMemoryManaged = await isGatewayMemoryManaged(model);
40690
40701
  state[GATEWAY_STATE_KEY] = gatewayMemoryManaged;
40691
40702
  if (gatewayMemoryManaged) {
40692
40703
  await this.endActiveTurn(state);
40693
- omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory — skipping local processing`);
40704
+ omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory \u2014 skipping local processing`);
40694
40705
  return messageList;
40695
40706
  }
40696
40707
  const { threadId, resourceId } = context;
@@ -40911,7 +40922,7 @@ var ObservationalMemoryProcessor = class {
40911
40922
  if (!context) return;
40912
40923
  if (parseMemoryRequestContext(requestContext)?.memoryConfig?.readOnly) return;
40913
40924
  state[CONTEXT_OVERFLOW_STEP_KEY] = stepNumber;
40914
- omDebug(`[OM:processAPIError] context overflow at step ${stepNumber} — observing pending messages`);
40925
+ omDebug(`[OM:processAPIError] context overflow at step ${stepNumber} \u2014 observing pending messages`);
40915
40926
  const { threadId, resourceId } = context;
40916
40927
  await this.engine.waitForBuffering(threadId, resourceId, void 0, args.abortSignal);
40917
40928
  const messages = getObservableMessages(messageList);