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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/dist/{a2a-BFN2C8f2.js → a2a-BfWMjFe2.js} +1 -1
  2. package/dist/{a2a-DlEIsCZz.cjs → a2a-DQIwTZyo.cjs} +1 -1
  3. package/dist/{agent-builder-Bd6qGrt6.js → agent-builder-DpuK5-6A.js} +2 -2
  4. package/dist/{agent-builder-Bz1beuPE.cjs → agent-builder-NSemjs4B.cjs} +2 -2
  5. package/dist/{agent-controller-BHJDvCaS.cjs → agent-controller-BP-CFfsg.cjs} +9 -9
  6. package/dist/{agent-controller-NRR6SK66.js → agent-controller-CzKnfKkw.js} +9 -9
  7. package/dist/{agent-versions-CwWhEoU5.cjs → agent-versions-0q4KKmLv.cjs} +12 -12
  8. package/dist/{agent-versions-DfcKpYNW.js → agent-versions-Pml6WNbA.js} +12 -12
  9. package/dist/{agents-DiQ_L6BU.cjs → agents-BO1mcMDf.cjs} +31 -9
  10. package/dist/{agents-BMdbohgU.js → agents-YvaBPFiS.js} +31 -9
  11. package/dist/{api-schema-manifest-BuAf53GH.cjs → api-schema-manifest-016lHJO2.cjs} +1 -1
  12. package/dist/{api-schema-manifest-CsefW4Vv.js → api-schema-manifest-CAZsA5Lk.js} +1 -1
  13. package/dist/{catalogue-CAIZ08il.cjs → catalogue-Cf7Zz7zb.cjs} +11 -11
  14. package/dist/{catalogue-BtSLF1p2.js → catalogue-DN4dvU88.js} +11 -11
  15. package/dist/{conversations-Dzpv_Cgt.js → conversations-4ZO0Pjvk.js} +1 -1
  16. package/dist/{conversations-6v0VCbif.cjs → conversations-BaYtooZZ.cjs} +1 -1
  17. package/dist/{datasets-C1XJLHN8.js → datasets-CYdtUF8e.js} +4 -1
  18. package/dist/{datasets-hqDd4IUN.cjs → datasets-CZRqni0N.cjs} +4 -1
  19. package/dist/dist-Bz6gINFc.js +1 -0
  20. package/dist/{dist-C5rwoPuL.cjs → dist-DaRCrkAU.cjs} +514 -238
  21. package/dist/{dist-C0Das1QD.cjs → dist-uiPbWl5E.cjs} +1 -1
  22. package/dist/{dist-Czbww9cr.js → dist-yny1avqv.js} +514 -238
  23. package/dist/docs/SKILL.md +1 -1
  24. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  25. package/dist/docs/references/reference-observability-tracing-advanced-queries.md +20 -0
  26. package/dist/{dynamic-workflows-DPgV6qtS.cjs → dynamic-workflows-CEKdGcSr.cjs} +4 -4
  27. package/dist/{dynamic-workflows-DmkCJ4Lp.js → dynamic-workflows-DF9X_oDG.js} +4 -4
  28. package/dist/{editor-builder-Cx9ZiHBw.cjs → editor-builder-ChYG8YTs.cjs} +1 -1
  29. package/dist/{editor-builder-DpNB1W4s.js → editor-builder-CwsIbd0F.js} +1 -1
  30. package/dist/{observability-zr7LDCQG.js → observability-URaJnI_U.js} +1 -1
  31. package/dist/{observability-Cn4P60P4.cjs → observability-zNA_CVaz.cjs} +1 -1
  32. package/dist/{plans-BoUO4vWD.js → plans-CbR8EDiT.js} +1 -1
  33. package/dist/{plans-DYNE2s8s.cjs → plans-k3UN9Nd1.cjs} +1 -1
  34. package/dist/probe-image-size-DZvSdjzK.js +13297 -0
  35. package/dist/probe-image-size-z8zXmjaH.cjs +13304 -0
  36. package/dist/{responses-ByDnfqlJ.cjs → responses-B-BKx236.cjs} +1 -1
  37. package/dist/{responses-CGv4KFQ3.js → responses-Blzxy0XP.js} +1 -1
  38. package/dist/{routes-C0TLNOPH.js → routes-D-I2voQe.js} +16 -16
  39. package/dist/{routes-BLjObOVE.cjs → routes-jiZyt9kU.cjs} +16 -16
  40. package/dist/{schedules-0ceTSdBB.cjs → schedules-CwL28Eca.cjs} +4 -4
  41. package/dist/{schedules-D_VfFdAH.js → schedules-RWgPeypN.js} +4 -4
  42. package/dist/{scorer-versions-Bhdvt-cX.cjs → scorer-versions-DK-PGj7-.cjs} +1 -1
  43. package/dist/{scorer-versions-DhT7Lj33.js → scorer-versions-oJoK2Exw.js} +1 -1
  44. package/dist/{scores-EVbkxGHy.cjs → scores-BikU9phm.cjs} +1 -1
  45. package/dist/{scores-CqNF-thA.js → scores-DAv6Uisq.js} +1 -1
  46. package/dist/server/handlers/a2a.cjs +1 -1
  47. package/dist/server/handlers/a2a.js +1 -1
  48. package/dist/server/handlers/agent-builder.cjs +1 -1
  49. package/dist/server/handlers/agent-builder.js +1 -1
  50. package/dist/server/handlers/agent-controller.cjs +1 -1
  51. package/dist/server/handlers/agent-controller.js +1 -1
  52. package/dist/server/handlers/agent-versions.cjs +1 -1
  53. package/dist/server/handlers/agent-versions.js +1 -1
  54. package/dist/server/handlers/agents.cjs +1 -1
  55. package/dist/server/handlers/agents.js +1 -1
  56. package/dist/server/handlers/auth.cjs +1 -1
  57. package/dist/server/handlers/auth.js +1 -1
  58. package/dist/server/handlers/conversations.cjs +1 -1
  59. package/dist/server/handlers/conversations.js +1 -1
  60. package/dist/server/handlers/datasets.cjs +16 -11
  61. package/dist/server/handlers/datasets.d.ts +6 -0
  62. package/dist/server/handlers/datasets.js +16 -11
  63. package/dist/server/handlers/dynamic-workflows.cjs +1 -1
  64. package/dist/server/handlers/dynamic-workflows.js +1 -1
  65. package/dist/server/handlers/editor-builder.cjs +1 -1
  66. package/dist/server/handlers/editor-builder.js +1 -1
  67. package/dist/server/handlers/favorites-enrichment.cjs +1 -1
  68. package/dist/server/handlers/favorites-enrichment.js +1 -1
  69. package/dist/server/handlers/observability.cjs +1 -1
  70. package/dist/server/handlers/observability.js +1 -1
  71. package/dist/server/handlers/plans.cjs +1 -1
  72. package/dist/server/handlers/plans.js +1 -1
  73. package/dist/server/handlers/responses.cjs +1 -1
  74. package/dist/server/handlers/responses.js +1 -1
  75. package/dist/server/handlers/schedules.cjs +1 -1
  76. package/dist/server/handlers/schedules.js +1 -1
  77. package/dist/server/handlers/scorer-versions.cjs +1 -1
  78. package/dist/server/handlers/scorer-versions.js +1 -1
  79. package/dist/server/handlers/scores.cjs +1 -1
  80. package/dist/server/handlers/scores.js +1 -1
  81. package/dist/server/handlers/stored-agent-favorites.cjs +3 -3
  82. package/dist/server/handlers/stored-agent-favorites.js +3 -3
  83. package/dist/server/handlers/stored-agents.cjs +2 -2
  84. package/dist/server/handlers/stored-agents.js +2 -2
  85. package/dist/server/handlers/stored-scorers.cjs +1 -1
  86. package/dist/server/handlers/stored-scorers.js +1 -1
  87. package/dist/server/handlers/stored-skill-favorites.cjs +2 -2
  88. package/dist/server/handlers/stored-skill-favorites.js +2 -2
  89. package/dist/server/handlers/stored-skills.cjs +1 -1
  90. package/dist/server/handlers/stored-skills.js +1 -1
  91. package/dist/server/handlers/system.cjs +1 -1
  92. package/dist/server/handlers/system.js +1 -1
  93. package/dist/server/handlers/tool-providers.cjs +2 -2
  94. package/dist/server/handlers/tool-providers.js +2 -2
  95. package/dist/server/handlers/tools.cjs +1 -1
  96. package/dist/server/handlers/tools.js +1 -1
  97. package/dist/server/handlers/voice.cjs +1 -1
  98. package/dist/server/handlers/voice.js +1 -1
  99. package/dist/server/handlers/workflows.cjs +1 -1
  100. package/dist/server/handlers/workflows.js +1 -1
  101. package/dist/server/handlers.cjs +12 -12
  102. package/dist/server/handlers.js +12 -12
  103. package/dist/server/schemas/datasets.d.ts +3 -0
  104. package/dist/server/schemas/index.cjs +6 -6
  105. package/dist/server/schemas/index.js +6 -6
  106. package/dist/server/server-adapter/index.cjs +3 -3
  107. package/dist/server/server-adapter/index.js +3 -3
  108. package/dist/server/server-adapter/routes/datasets.d.ts +6 -0
  109. package/dist/{server-adapter-BkAKl970.cjs → server-adapter-BB2Lw2Ig.cjs} +4 -4
  110. package/dist/{server-adapter-CxMHZZAv.js → server-adapter-CMJcvkpD.js} +4 -4
  111. package/dist/{stored-agents-m0Knvv29.cjs → stored-agents-BS4_LGSs.cjs} +32 -32
  112. package/dist/{stored-agents-DmN_pIIl.js → stored-agents-DcyDMKP2.js} +32 -32
  113. package/dist/{stored-scorers-2F2k6XSx.js → stored-scorers-Bdz_5k57.js} +1 -1
  114. package/dist/{stored-scorers-iM2Qq9Nh.cjs → stored-scorers-D8YYszOj.cjs} +1 -1
  115. package/dist/{tool-providers-Cq3vFqgE.js → tool-providers-BN2Ni06Z.js} +2 -2
  116. package/dist/{tool-providers-BVwRJTtB.cjs → tool-providers-BeiSkVHu.cjs} +2 -2
  117. package/dist/{tools-D07qyAT0.cjs → tools-CoamSJif.cjs} +1 -1
  118. package/dist/{tools-CZmeb9MB.js → tools-DsSk01Ti.js} +1 -1
  119. package/dist/{voice-BNwHCtxv.js → voice-BFh2Zx5m.js} +1 -1
  120. package/dist/{voice-DN72TM58.cjs → voice-CquR7YyA.cjs} +1 -1
  121. package/dist/{workflows-gIKukZ1O.cjs → workflows-CHKSHV4f.cjs} +33 -0
  122. package/dist/{workflows-D3QrUMfm.js → workflows-D5bfbang.js} +33 -0
  123. package/package.json +3 -3
  124. package/dist/dist-C_7xKME1.js +0 -1
  125. package/dist/probe-image-size-C0BvSeqt.js +0 -13297
  126. package/dist/probe-image-size-DQsyQSUh.cjs +0 -13304
@@ -7,12 +7,12 @@ zod_v4 = require_rolldown_runtime.__toESM(zod_v4, 1);
7
7
  let _mastra_core_schema = require("@mastra/core/schema");
8
8
  let zod_v3 = require("zod/v3");
9
9
  let zod = require("zod");
10
+ let util = require("util");
10
11
  let _mastra_core_memory = require("@mastra/core/memory");
11
12
  let _mastra_core_agent = require("@mastra/core/agent");
12
13
  let _mastra_core_error = require("@mastra/core/error");
13
14
  let _mastra_core_llm = require("@mastra/core/llm");
14
15
  let _mastra_core_tools = require("@mastra/core/tools");
15
- let util = require("util");
16
16
  let _mastra_core_request_context = require("@mastra/core/request-context");
17
17
  let _mastra_core_utils = require("@mastra/core/utils");
18
18
  let _mastra_core_storage = require("@mastra/core/storage");
@@ -897,7 +897,7 @@ var require_jpeg = /* @__PURE__ */ require_rolldown_runtime.__commonJSMin(((expo
897
897
  var str2arr = require_utils().str2arr;
898
898
  var sliceEq = require_utils().sliceEq;
899
899
  var exifOrientation = require_exif_orientation_parser();
900
- var SIG_JPEG = str2arr("ÿØÿ");
900
+ var SIG_JPEG = str2arr("\u00FF\u00D8\u00FF");
901
901
  var SIG_EXIF = str2arr("Exif\0\0");
902
902
  var S_SIGNATURE = 0;
903
903
  var S_MARKER_START = 1;
@@ -1043,7 +1043,7 @@ var require_png = /* @__PURE__ */ require_rolldown_runtime.__commonJSMin(((expor
1043
1043
  var str2arr = require_utils().str2arr;
1044
1044
  var sliceEq = require_utils().sliceEq;
1045
1045
  var readUInt32BE = require_read_le_be().readUInt32BE;
1046
- var SIG_PNG = str2arr("‰PNG\r\n\n");
1046
+ var SIG_PNG = str2arr("\u0089PNG\r\n\n");
1047
1047
  var SIG_IHDR = str2arr("IHDR");
1048
1048
  function PngParser() {
1049
1049
  this.partial_buffer = /* @__PURE__ */ new Uint8Array(24);
@@ -8656,7 +8656,7 @@ function splitLines(text) {
8656
8656
  else result.push(result.pop().slice(0, -1));
8657
8657
  return result;
8658
8658
  }
8659
- // ../memory/dist/src-CRmfe-8x.js
8659
+ // ../memory/dist/src-TRQ73bGO.js
8660
8660
  var __defProp$3 = Object.defineProperty;
8661
8661
  var __exportAll = (all, no_symbols) => {
8662
8662
  let target = {};
@@ -32877,14 +32877,14 @@ function getRetrievalInstructions(scope = "resource", customInstructions, search
32877
32877
  The recall tool works across ALL of this user's conversation threads, not just the current one.
32878
32878
 
32879
32879
  - 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.
32880
- - 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.
32880
+ - 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.
32881
32881
  - 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.
32882
32882
 
32883
- **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
32883
+ **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
32884
32884
  The recall tool works across ALL of this user's conversation threads, not just the current one.
32885
32885
 
32886
32886
  - 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.
32887
- - Use \`mode: "messages"\` when you know the thread — pass \`threadId\` to read another thread, or a \`cursor\` from an observation-group range.
32887
+ - Use \`mode: "messages"\` when you know the thread \u2014 pass \`threadId\` to read another thread, or a \`cursor\` from an observation-group range.
32888
32888
 
32889
32889
  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
32890
32890
  The recall tool is limited to the current conversation thread.
@@ -32909,7 +32909,7 @@ When searches keep returning the same groups, often as already-in-context refere
32909
32909
  "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.
32910
32910
 
32911
32911
  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.` : "";
32912
- const base = `## Recall — looking up source messages
32912
+ const base = `## Recall \u2014 looking up source messages
32913
32913
 
32914
32914
  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.
32915
32915
 
@@ -32920,13 +32920,13 @@ Groups marked \`kind="reflection"\` (rendered as \`_kind: reflection_\`) are los
32920
32920
 
32921
32921
  ### When to use recall
32922
32922
  - The user asks you to **repeat, show, or reproduce** something from a past conversation
32923
- - The user asks for **exact content** — code, text, quotes, error messages, URLs, file paths, specific numbers
32923
+ - The user asks for **exact content** \u2014 code, text, quotes, error messages, URLs, file paths, specific numbers
32924
32924
  - 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)
32925
32925
  - You want to **verify or expand on** an observation before responding
32926
32926
  - 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
32927
32927
  - 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
32928
32928
  - Relevant details are missing, ambiguous, or conflicting in the current observations${isResource ? `
32929
- - The user references another conversation that your observations don't cover — even if you have no observations yet, their other threads may contain it` : ""}
32929
+ - 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` : ""}
32930
32930
 
32931
32931
  **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.
32932
32932
 
@@ -32961,17 +32961,17 @@ Each range has the format \`startId:endId\` where both are message IDs separated
32961
32961
  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.
32962
32962
 
32963
32963
  - 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.
32964
- - 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.
32964
+ - 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.
32965
32965
 
32966
32966
  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.
32967
32967
 
32968
32968
  ### Following up on truncated parts
32969
32969
  Low-detail results may include truncation hints like:
32970
- \`[truncated — call recall cursor="..." partIndex=N detail="high" for full content]\`
32970
+ \`[truncated \u2014 call recall cursor="..." partIndex=N detail="high" for full content]\`
32971
32971
 
32972
32972
  **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.
32973
32973
 
32974
- 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.
32974
+ 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.
32975
32975
 
32976
32976
  ### When recall is NOT needed
32977
32977
  - The user is asking for a high-level summary and your observations already cover it
@@ -33366,6 +33366,15 @@ function buildThreadMetadataFromExtractedValues(extractors, values) {
33366
33366
  async function applyExtractorHooks(opts) {
33367
33367
  const values = normalizeExtractedValues(opts.values) ?? {};
33368
33368
  const failures = [...opts.failures ?? []];
33369
+ let recentMessages;
33370
+ let recentMessagesResolved = false;
33371
+ const resolveRecentMessages = () => {
33372
+ if (!recentMessagesResolved) {
33373
+ recentMessages = typeof opts.recentMessages === "function" ? opts.recentMessages() : opts.recentMessages;
33374
+ recentMessagesResolved = true;
33375
+ }
33376
+ return recentMessages;
33377
+ };
33369
33378
  for (const extractor of opts.extractors) {
33370
33379
  const isHook = extractor.mode === "hook";
33371
33380
  const hasValue = Object.prototype.hasOwnProperty.call(values, extractor.slug);
@@ -33385,7 +33394,9 @@ async function applyExtractorHooks(opts) {
33385
33394
  previous: isHook ? void 0 : opts.previousValues?.[extractor.slug],
33386
33395
  current,
33387
33396
  rawObservations: opts.rawObservations,
33388
- recentMessages: opts.recentMessages,
33397
+ get recentMessages() {
33398
+ return resolveRecentMessages();
33399
+ },
33389
33400
  mainAgent: opts.mainAgent,
33390
33401
  memory: opts.memory,
33391
33402
  sendSignal: opts.sendSignal,
@@ -34089,7 +34100,7 @@ const YEAR = String.raw`(?:19|20|21)\d{2}(?!\d)`;
34089
34100
  const MERIDIEM = String.raw`(?:[AaPp]\.[Mm]\.|[AaPp][Mm]\b)`;
34090
34101
  const TIME = String.raw`(?:,?\s+(?:at\s+)?\d{1,2}:\d{2}(?:\s*${MERIDIEM})?|\s+at\s+\d{1,2}\s*${MERIDIEM})`;
34091
34102
  const QUALIFIER = String.raw`(?:(?:early|mid|late)[- ](?:to[- ](?:early|mid|late)[- ])?)`;
34092
- const RANGE_SEP = String.raw`(?:\s*[–—]\s*|\s*-\s*|\s+(?:to|through|until)\s+)`;
34103
+ const RANGE_SEP = String.raw`(?:\s*[\u2013\u2014]\s*|\s*-\s*|\s+(?:to|through|until)\s+)`;
34093
34104
  /**
34094
34105
  * Dates written into observation text that carry their own year, longest forms first:
34095
34106
  * "Mar 1 - Mar 18, 2025", "May 27-28, 2023", "January 10, 2024 at 3:00 PM",
@@ -34390,15 +34401,15 @@ const SHORT_TOKEN_THRESHOLD = 3;
34390
34401
  const KANA_CHARS_PER_TOKEN = 1.35;
34391
34402
  const DEFAULT_LANGUAGE_CONFIGS = [
34392
34403
  {
34393
- pattern: /[äöüßẞ]/i,
34404
+ pattern: /[\u00E4\u00F6\u00FC\u00DF\u1E9E]/i,
34394
34405
  averageCharsPerToken: 2.6
34395
34406
  },
34396
34407
  {
34397
- pattern: /[éèêëàâîïôûùüÿçœæáíóúñ]/i,
34408
+ pattern: /[\u00E9\u00E8\u00EA\u00EB\u00E0\u00E2\u00EE\u00EF\u00F4\u00FB\u00F9\u00FC\u00FF\u00E7\u0153\u00E6\u00E1\u00ED\u00F3\u00FA\u00F1]/i,
34398
34409
  averageCharsPerToken: 3
34399
34410
  },
34400
34411
  {
34401
- pattern: /[ąćęłńóśźżěščřžýůúďťň]/i,
34412
+ pattern: /[\u0105\u0107\u0119\u0142\u0144\u00F3\u015B\u017A\u017C\u011B\u0161\u010D\u0159\u017E\u00FD\u016F\u00FA\u010F\u0165\u0148]/i,
34402
34413
  averageCharsPerToken: 2.5
34403
34414
  },
34404
34415
  {
@@ -34486,10 +34497,10 @@ function sanitizeSurrogates(value) {
34486
34497
  if (next >= 56320 && next <= 57343) {
34487
34498
  sanitized += value.charAt(index) + value.charAt(index + 1);
34488
34499
  index++;
34489
- } else sanitized += "�";
34500
+ } else sanitized += "\uFFFD";
34490
34501
  continue;
34491
34502
  }
34492
- sanitized += code >= 56320 && code <= 57343 ? "�" : value[index];
34503
+ sanitized += code >= 56320 && code <= 57343 ? "\uFFFD" : value[index];
34493
34504
  }
34494
34505
  return sanitized;
34495
34506
  }
@@ -34511,7 +34522,7 @@ function truncatePath(path) {
34511
34522
  const headLength = 50;
34512
34523
  const tailLength = 60;
34513
34524
  const omitted = path.length - headLength - tailLength;
34514
- return `${safeSlice(path, headLength)}…[${omitted} chars; ${stablePathDigest(path)}]…${safeTail(path, tailLength)}`;
34525
+ return `${safeSlice(path, headLength)}\u2026[${omitted} chars; ${stablePathDigest(path)}]\u2026${safeTail(path, tailLength)}`;
34515
34526
  }
34516
34527
  function formatPath(parent, key, isArray) {
34517
34528
  if (isArray) return truncatePath(`${parent}[${key}]`);
@@ -34620,7 +34631,7 @@ function selectOutlineEntries(entries, limits) {
34620
34631
  const rendered = joinEntries(selected, marker);
34621
34632
  if (fits(rendered, limits)) return rendered;
34622
34633
  if (fits(marker, limits)) return marker;
34623
- return fits("…", limits) ? "…" : "";
34634
+ return fits("\u2026", limits) ? "\u2026" : "";
34624
34635
  }
34625
34636
  function indentPreview(value) {
34626
34637
  return value.split("\n").map((line) => ` | ${line}`).join("\n");
@@ -34663,13 +34674,13 @@ function formatToolArgumentsForObserver(value, options) {
34663
34674
  if (!isObjectLike$1(value)) {
34664
34675
  if (typeof value !== "string" || value.length <= OBSERVER_TOOL_ARGUMENT_INLINE_STRING_MAX_CHARS) {
34665
34676
  const primitive = formatPrimitive(value);
34666
- return fits(primitive, limits) ? primitive : fits("…", limits) ? "…" : "";
34677
+ return fits(primitive, limits) ? primitive : fits("\u2026", limits) ? "\u2026" : "";
34667
34678
  }
34668
34679
  const summary = `<string, ${value.length} characters; preview size-limited>`;
34669
34680
  const rendered = appendWithinBudget(summary, formatPreview("preview", value, limits, summary), limits);
34670
34681
  if (rendered) return rendered;
34671
34682
  if (fits(summary, limits)) return summary;
34672
- return fits("…", limits) ? "…" : "";
34683
+ return fits("\u2026", limits) ? "\u2026" : "";
34673
34684
  }
34674
34685
  const outline = [];
34675
34686
  const previews = [];
@@ -34913,24 +34924,24 @@ function formatToolResultForObserver(value, options) {
34913
34924
  const OBSERVER_EXTRACTION_INSTRUCTIONS = `CRITICAL: DISTINGUISH USER ASSERTIONS FROM QUESTIONS
34914
34925
 
34915
34926
  When the user TELLS you something about themselves, mark it as an assertion:
34916
- - "I have two kids" → 🔴 (14:30) User stated has two kids
34917
- - "I work at Acme Corp" → 🔴 (14:31) User stated works at Acme Corp
34918
- - "I graduated in 2019" → 🔴 (14:32) User stated graduated in 2019
34927
+ - "I have two kids" \u2192 \u{1F534} (14:30) User stated has two kids
34928
+ - "I work at Acme Corp" \u2192 \u{1F534} (14:31) User stated works at Acme Corp
34929
+ - "I graduated in 2019" \u2192 \u{1F534} (14:32) User stated graduated in 2019
34919
34930
 
34920
34931
  When the user ASKS about something, mark it as a question/request:
34921
- - "Can you help me with X?" → 🔴 (15:00) User asked help with X
34922
- - "What's the best way to do Y?" → 🔴 (15:01) User asked best way to do Y
34932
+ - "Can you help me with X?" \u2192 \u{1F534} (15:00) User asked help with X
34933
+ - "What's the best way to do Y?" \u2192 \u{1F534} (15:01) User asked best way to do Y
34923
34934
 
34924
34935
  Distinguish between QUESTIONS and STATEMENTS OF INTENT:
34925
- - "Can you recommend..." → Question (extract as "User asked...")
34926
- - "I'm looking forward to [doing X]" → Statement of intent (extract as "User stated they will [do X] (include estimated/actual date if mentioned)")
34927
- - "I need to [do X]" → Statement of intent (extract as "User stated they need to [do X] (again, add date if mentioned)")
34936
+ - "Can you recommend..." \u2192 Question (extract as "User asked...")
34937
+ - "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)")
34938
+ - "I need to [do X]" \u2192 Statement of intent (extract as "User stated they need to [do X] (again, add date if mentioned)")
34928
34939
 
34929
34940
  STATE CHANGES AND UPDATES:
34930
34941
  When a user indicates they are changing something, frame it as a state change that supersedes previous information:
34931
- - "I'm going to start doing X instead of Y" → "User will start doing X (changing from Y)"
34932
- - "I'm switching from A to B" → "User is switching from A to B"
34933
- - "I moved my stuff to the new place" → "User moved their stuff to the new place (no longer at previous location)"
34942
+ - "I'm going to start doing X instead of Y" \u2192 "User will start doing X (changing from Y)"
34943
+ - "I'm switching from A to B" \u2192 "User is switching from A to B"
34944
+ - "I moved my stuff to the new place" \u2192 "User moved their stuff to the new place (no longer at previous location)"
34934
34945
 
34935
34946
  If the new state contradicts or updates previous information, make that explicit:
34936
34947
  - BAD: "User plans to use the new method"
@@ -35021,11 +35032,11 @@ BAD: User got something.
35021
35032
  GOOD: User purchased / received / was given something. (be specific)
35022
35033
 
35023
35034
  Common clarifications:
35024
- - "getting" something regularly → "subscribed to" or "enrolled in"
35025
- - "getting" something once → "purchased" or "acquired"
35026
- - "got" → "purchased", "received as gift", "was given", "picked up"
35027
- - "signed up" → "enrolled in", "registered for", "subscribed to"
35028
- - "stopped getting" → "canceled", "unsubscribed from", "discontinued"
35035
+ - "getting" something regularly \u2192 "subscribed to" or "enrolled in"
35036
+ - "getting" something once \u2192 "purchased" or "acquired"
35037
+ - "got" \u2192 "purchased", "received as gift", "was given", "picked up"
35038
+ - "signed up" \u2192 "enrolled in", "registered for", "subscribed to"
35039
+ - "stopped getting" \u2192 "canceled", "unsubscribed from", "discontinued"
35029
35040
 
35030
35041
  When the assistant interprets or confirms the user's vague language, prefer the assistant's precise terminology.
35031
35042
 
@@ -35110,16 +35121,16 @@ AVOIDING REPETITIVE OBSERVATIONS:
35110
35121
  - Do NOT repeat the same observation across multiple turns if there is no new information.
35111
35122
  - 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.
35112
35123
 
35113
- Example — BAD (repetitive):
35114
- * 🟡 (14:30) Agent used view tool on src/auth.ts
35115
- * 🟡 (14:31) Agent used view tool on src/users.ts
35116
- * 🟡 (14:32) Agent used view tool on src/routes.ts
35124
+ Example \u2014 BAD (repetitive):
35125
+ * \u{1F7E1} (14:30) Agent used view tool on src/auth.ts
35126
+ * \u{1F7E1} (14:31) Agent used view tool on src/users.ts
35127
+ * \u{1F7E1} (14:32) Agent used view tool on src/routes.ts
35117
35128
 
35118
- Example — GOOD (grouped):
35119
- * 🟡 (14:30) Agent browsed source files for auth flow
35120
- * -> viewed src/auth.ts — found token validation logic
35121
- * -> viewed src/users.ts — found user lookup by email
35122
- * -> viewed src/routes.ts — found middleware chain
35129
+ Example \u2014 GOOD (grouped):
35130
+ * \u{1F7E1} (14:30) Agent browsed source files for auth flow
35131
+ * -> viewed src/auth.ts \u2014 found token validation logic
35132
+ * -> viewed src/users.ts \u2014 found user lookup by email
35133
+ * -> viewed src/routes.ts \u2014 found middleware chain
35123
35134
 
35124
35135
  Only add a new observation for a repeated action if the NEW result changes the picture.
35125
35136
 
@@ -35132,29 +35143,29 @@ COMPLETION TRACKING:
35132
35143
  Completion observations are not just summaries. They are explicit memory signals to the assistant that a task, question, or subtask has been resolved.
35133
35144
  Without clear completion markers, the assistant may forget that work is already finished and may repeat, reopen, or continue an already-completed task.
35134
35145
 
35135
- Use ✅ to answer: "What exactly is now done?"
35146
+ Use \u2705 to answer: "What exactly is now done?"
35136
35147
  Choose completion observations that help the assistant know what is finished and should not be reworked unless new information appears.
35137
35148
 
35138
- Use ✅ when:
35149
+ Use \u2705 when:
35139
35150
  - The user explicitly confirms something worked or was answered ("thanks, that fixed it", "got it", "perfect")
35140
35151
  - The assistant provided a definitive, complete answer to a factual question and the user moved on
35141
35152
  - A multi-step task reached its stated goal
35142
35153
  - The user acknowledged receipt of requested information
35143
35154
  - A concrete subtask, fix, deliverable, or implementation step became complete during ongoing work
35144
35155
 
35145
- Do NOT use ✅ when:
35146
- - The assistant merely responded — the user might follow up with corrections
35156
+ Do NOT use \u2705 when:
35157
+ - The assistant merely responded \u2014 the user might follow up with corrections
35147
35158
  - The topic is paused but not resolved ("I'll try that later")
35148
35159
  - The user's reaction is ambiguous
35149
35160
 
35150
35161
  FORMAT:
35151
35162
  As a sub-bullet under the related observation group:
35152
- * 🔴 (14:30) User asked how to configure auth middleware
35163
+ * \u{1F534} (14:30) User asked how to configure auth middleware
35153
35164
  * -> Agent explained JWT setup with code example
35154
- * ✅ User confirmed auth is working
35165
+ * \u2705 User confirmed auth is working
35155
35166
 
35156
35167
  Or as a standalone observation when closing out a broader task:
35157
- * ✅ (14:45) Auth configuration task completed — user confirmed middleware is working
35168
+ * \u2705 (14:45) Auth configuration task completed \u2014 user confirmed middleware is working
35158
35169
 
35159
35170
  Completion observations should be terse but specific about WHAT was completed.
35160
35171
  Prefer concrete resolved outcomes over abstract workflow status so the assistant remembers what is already done.`;
@@ -35171,28 +35182,28 @@ buildObserverOutputFormat();
35171
35182
  */
35172
35183
  function buildObserverOutputFormat(extractors) {
35173
35184
  return `Use priority levels:
35174
- - 🔴 High: explicit user facts, preferences, unresolved goals, critical context
35175
- - 🟡 Medium: project details, learned information, tool results
35176
- - 🟢 Low: minor details, uncertain observations
35177
- - ✅ Completed: concrete task finished, question answered, issue resolved, goal achieved, or subtask completed in a way that helps the assistant know it is done
35185
+ - \u{1F534} High: explicit user facts, preferences, unresolved goals, critical context
35186
+ - \u{1F7E1} Medium: project details, learned information, tool results
35187
+ - \u{1F7E2} Low: minor details, uncertain observations
35188
+ - \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
35178
35189
 
35179
35190
  Group related observations (like tool sequences) by indenting:
35180
- * 🔴 (14:33) Agent debugging auth issue
35191
+ * \u{1F534} (14:33) Agent debugging auth issue
35181
35192
  * -> ran git status, found 3 modified files
35182
35193
  * -> viewed auth.ts:45-60, found missing null check
35183
35194
  * -> applied fix, tests now pass
35184
- * ✅ Tests passing, auth issue resolved
35195
+ * \u2705 Tests passing, auth issue resolved
35185
35196
 
35186
35197
  Group observations by date. Within a date, list observations in the order the events happened (not by importance), each with 24-hour time.
35187
35198
 
35188
35199
  <observations>
35189
35200
  Date: Dec 4, 2025
35190
- * 🔴 (14:30) User prefers direct answers
35191
- * 🔴 (14:31) Working on feature X
35192
- * 🟡 (14:32) User might prefer dark mode
35201
+ * \u{1F534} (14:30) User prefers direct answers
35202
+ * \u{1F534} (14:31) Working on feature X
35203
+ * \u{1F7E1} (14:32) User might prefer dark mode
35193
35204
 
35194
35205
  Date: Dec 5, 2025
35195
- * 🔴 (09:15) Continued work on feature X
35206
+ * \u{1F534} (09:15) Continued work on feature X
35196
35207
  </observations>
35197
35208
 
35198
35209
  ${buildExtractorOutputSections(extractors ?? []) || (extractors === void 0 ? `
@@ -35222,9 +35233,9 @@ const OBSERVER_GUIDELINES = `- Be specific enough for the assistant to act on
35222
35233
  - If the agent calls tools, observe what was called, why, and what was learned
35223
35234
  - When observing files with line numbers, include the line number if useful
35224
35235
  - If the agent provides a detailed response, observe the contents so it could be repeated
35225
- - Make sure you start each observation with a priority emoji (🔴, 🟡, 🟢) or a completion marker (✅)
35226
- - 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 🔴
35227
- - Treat ✅ as a memory signal that tells the assistant something is finished and should not be repeated unless new information changes it
35236
+ - Make sure you start each observation with a priority emoji (\u{1F534}, \u{1F7E1}, \u{1F7E2}) or a completion marker (\u2705)
35237
+ - 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}
35238
+ - Treat \u2705 as a memory signal that tells the assistant something is finished and should not be repeated unless new information changes it
35228
35239
  - Make completion observations answer "What exactly is now done?"
35229
35240
  - Prefer concrete resolved outcomes over meta-level workflow or bookkeeping updates
35230
35241
  - When multiple concrete things were completed, capture the concrete completed work rather than collapsing it into a vague progress summary
@@ -35278,8 +35289,8 @@ For multi-thread output, wrap each thread's observations like this:
35278
35289
  <observations>
35279
35290
  <thread id="thread_id_1">
35280
35291
  Date: Dec 4, 2025
35281
- * 🔴 (14:30) User prefers direct answers
35282
- * 🔴 (14:31) Working on feature X${currentTaskEnabled ? `
35292
+ * \u{1F534} (14:30) User prefers direct answers
35293
+ * \u{1F534} (14:31) Working on feature X${currentTaskEnabled ? `
35283
35294
 
35284
35295
  <current-task>
35285
35296
  What the agent is currently working on in this thread
@@ -35292,7 +35303,7 @@ Hint for the agent's next message in this thread
35292
35303
 
35293
35304
  <thread id="thread_id_2">
35294
35305
  Date: Dec 5, 2025
35295
- * 🔴 (09:15) User asked about deployment${currentTaskEnabled ? `
35306
+ * \u{1F534} (09:15) User asked about deployment${currentTaskEnabled ? `
35296
35307
 
35297
35308
  <current-task>
35298
35309
  Current task for this thread
@@ -36123,7 +36134,7 @@ function sanitizeObservationLines(observations) {
36123
36134
  const lines = observations.split("\n");
36124
36135
  let changed = false;
36125
36136
  for (let i = 0; i < lines.length; i++) if (lines[i].length > MAX_OBSERVATION_LINE_CHARS) {
36126
- lines[i] = safeSlice(lines[i], MAX_OBSERVATION_LINE_CHARS) + " … [truncated]";
36137
+ lines[i] = safeSlice(lines[i], MAX_OBSERVATION_LINE_CHARS) + " \u2026 [truncated]";
36127
36138
  changed = true;
36128
36139
  }
36129
36140
  return changed ? lines.join("\n") : observations;
@@ -36321,8 +36332,8 @@ function describeDegenerateOutput(text, snippetChars = 400) {
36321
36332
  */
36322
36333
  function optimizeObservationsForContext(observations) {
36323
36334
  let optimized = stripEphemeralAnchorIds(observations);
36324
- optimized = optimized.replace(/🟡\s*/g, "");
36325
- optimized = optimized.replace(/🟢\s*/g, "");
36335
+ optimized = optimized.replace(/\uD83D\uDFE1\s*/g, "");
36336
+ optimized = optimized.replace(/\uD83D\uDFE2\s*/g, "");
36326
36337
  optimized = optimized.replace(/\s*->\s*/g, " ");
36327
36338
  optimized = optimized.replace(/ +/g, " ");
36328
36339
  optimized = optimized.replace(/\n{3,}/g, "\n\n");
@@ -37278,7 +37289,7 @@ async function resolveImageDimensionsAsync(part) {
37278
37289
  const url = resolveHttpAssetUrl(getObjectValue(part, "image") ?? getObjectValue(part, "data"));
37279
37290
  if (!url) return existing;
37280
37291
  try {
37281
- const probeImageSize = (await Promise.resolve().then(() => /* @__PURE__ */ require_rolldown_runtime.__toESM(require("./probe-image-size-DQsyQSUh.cjs").default, 1))).default;
37292
+ const probeImageSize = (await Promise.resolve().then(() => /* @__PURE__ */ require_rolldown_runtime.__toESM(require("./probe-image-size-z8zXmjaH.cjs").default, 1))).default;
37282
37293
  const probed = await probeImageSize(url, {
37283
37294
  open_timeout: REMOTE_IMAGE_PROBE_TIMEOUT_MS,
37284
37295
  response_timeout: REMOTE_IMAGE_PROBE_TIMEOUT_MS,
@@ -38600,8 +38611,8 @@ const updateWorkingMemoryTool = (memoryConfig) => {
38600
38611
  }
38601
38612
  const usesMergeSemantics = Boolean(schema);
38602
38613
  const useStateSignals = memoryConfig?.workingMemory?.useStateSignals === true;
38603
- 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.`;
38604
- 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.`;
38614
+ 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.`;
38615
+ 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.`;
38605
38616
  return (0, _mastra_core_tools.createTool)({
38606
38617
  id: "update-working-memory",
38607
38618
  description,
@@ -39611,8 +39622,8 @@ async function pageGroups({ om, threadId, resourceId, groupId, recordId, directi
39611
39622
  })).count > 0;
39612
39623
  const hasLater = direction === "before" || hasMore;
39613
39624
  const newer = hasLater ? null : await newerMessagesNote(page.at(-1).group, countNewerMessages, pagingThreadId);
39614
- text.unshift(hasEarlier ? `— Browse earlier: ${pagingCall(page[0].group.id, "before", pagingThreadId, page[0].record.id)} —` : "— Start of retained observation history for this thread. —");
39615
- 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. —");
39625
+ 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");
39626
+ 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");
39616
39627
  text.unshift(`### Observation page\nThread: ${threadTitle || "(untitled)"}\nShowing ${page.length} groups ${requestedDirection === void 0 ? "starting at" : `strictly ${direction}`} \`${groupId}\` (oldest first).`);
39617
39628
  return {
39618
39629
  results: text.join("\n\n"),
@@ -39798,7 +39809,7 @@ async function listThreadsForResource({ memory, resourceId, currentThreadId, pag
39798
39809
  const title = thread.title || "(untitled)";
39799
39810
  const updated = formatTimestamp(thread.updatedAt);
39800
39811
  const created = formatTimestamp(thread.createdAt);
39801
- const marker = isCurrent ? " ← current" : "";
39812
+ const marker = isCurrent ? " \u2190 current" : "";
39802
39813
  lines.push(`- **${title}**${marker}`);
39803
39814
  lines.push(` id: ${thread.id}`);
39804
39815
  lines.push(` updated: ${updated} | created: ${created}`);
@@ -39977,7 +39988,7 @@ async function searchMessagesForResource({ memory, om, resourceId, currentThread
39977
39988
  const groupLine = match.groupId ? `- observation group: ${groupCursor(match.groupId, match.recordId)}` : void 0;
39978
39989
  const scoreLine = `- score: ${match.score.toFixed(2)}`;
39979
39990
  const prev = i > 0 ? ordered[i - 1].match : void 0;
39980
- 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)} —`);
39991
+ 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`);
39981
39992
  if (suppression) {
39982
39993
  sections.push(`${groupLine}\n thread: ${match.threadId}; ${suppression}`);
39983
39994
  continue;
@@ -40532,7 +40543,7 @@ async function recallAttachmentView({ memory, threadId, resourceId, cursor, part
40532
40543
  const partType = rawPart?.type;
40533
40544
  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.` };
40534
40545
  const resolvedAttachment = resolveViewableAttachment(rawPart);
40535
- if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)} — ${resolvedAttachment.note}` };
40546
+ if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)} \u2014 ${resolvedAttachment.note}` };
40536
40547
  return { content: [{
40537
40548
  type: "text",
40538
40549
  text: formatAttachmentPart(partType, rawPart)
@@ -40935,7 +40946,7 @@ const recallTool = (_memoryConfig, options) => {
40935
40946
  if (!thread) return { error: "Could not resolve current thread." };
40936
40947
  if (isResourceScope && resourceId && thread.resourceId !== resourceId) throw new Error("Thread does not belong to the active resource");
40937
40948
  return {
40938
- threads: `- **${thread.title || "(untitled)"}** ← current\n id: ${thread.id}\n updated: ${formatTimestamp(thread.updatedAt)} | created: ${formatTimestamp(thread.createdAt)}`,
40949
+ threads: `- **${thread.title || "(untitled)"}** \u2190 current\n id: ${thread.id}\n updated: ${formatTimestamp(thread.updatedAt)} | created: ${formatTimestamp(thread.createdAt)}`,
40939
40950
  count: 1,
40940
40951
  page: 0,
40941
40952
  hasMore: false
@@ -41498,6 +41509,79 @@ var BufferingCoordinator = class BufferingCoordinator {
41498
41509
  * Key format: "refl:{lockKey}"
41499
41510
  */
41500
41511
  static reflectionBufferCycleIds = /* @__PURE__ */ new Map();
41512
+ /**
41513
+ * The buffered-reflection op that set the reflection boundary and cycle, and the generation
41514
+ * it buffers for. Key format: "refl:{lockKey}"
41515
+ */
41516
+ static reflectionBufferOwners = /* @__PURE__ */ new Map();
41517
+ /** Set the reflection boundary for a new buffered-reflection op on generation `recordId`. */
41518
+ static startReflectionBuffer(bufferKey, tokens, recordId) {
41519
+ const owner = {
41520
+ recordId,
41521
+ retired: false
41522
+ };
41523
+ BufferingCoordinator.lastBufferedBoundary.set(bufferKey, tokens);
41524
+ BufferingCoordinator.reflectionBufferOwners.set(bufferKey, owner);
41525
+ return owner;
41526
+ }
41527
+ /** Drop this process's reflection boundary, cycle, and owner. */
41528
+ static clearReflectionBuffer(bufferKey) {
41529
+ BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
41530
+ BufferingCoordinator.reflectionBufferCycleIds.delete(bufferKey);
41531
+ BufferingCoordinator.reflectionBufferOwners.delete(bufferKey);
41532
+ }
41533
+ /**
41534
+ * Another writer retired generation `recordId`, so a buffer this process prepared for it can
41535
+ * never activate. Its boundary and cycle are dropped now, or, while the op that set them is
41536
+ * still running (it may be awaiting its `onReflectionEnd` hook), when that op finishes. State
41537
+ * owned by a newer generation is kept.
41538
+ */
41539
+ static retireReflectionBuffer(bufferKey, recordId) {
41540
+ const owner = BufferingCoordinator.reflectionBufferOwners.get(bufferKey);
41541
+ if (owner && owner.recordId !== recordId) return;
41542
+ if (owner && BufferingCoordinator.asyncBufferingOps.has(bufferKey)) {
41543
+ owner.retired = true;
41544
+ return;
41545
+ }
41546
+ BufferingCoordinator.clearReflectionBuffer(bufferKey);
41547
+ }
41548
+ /**
41549
+ * Reconcile this process's reflection buffer state against an observed head record.
41550
+ * Whenever `head.id` differs from `owner.recordId`, confirm against a fresh storage read started
41551
+ * after `owner` existed (never trusting `generationCount`, which resets to 0 after `clear()`):
41552
+ * only retire/clear when storage's live head is no longer `owner.recordId`.
41553
+ */
41554
+ static async reconcileReflectionBufferHead(bufferKey, headId, readLiveHead) {
41555
+ const owner = BufferingCoordinator.reflectionBufferOwners.get(bufferKey);
41556
+ if (!owner || owner.recordId === headId) return;
41557
+ const ownerRecordId = owner.recordId;
41558
+ const live = await readLiveHead();
41559
+ if (BufferingCoordinator.reflectionBufferOwners.get(bufferKey) !== owner || owner.recordId !== ownerRecordId) return;
41560
+ if (live?.id === ownerRecordId) return;
41561
+ if (BufferingCoordinator.asyncBufferingOps.has(bufferKey)) {
41562
+ owner.retired = true;
41563
+ return;
41564
+ }
41565
+ BufferingCoordinator.clearReflectionBuffer(bufferKey);
41566
+ }
41567
+ /**
41568
+ * Take the buffered-reflection cycle id for generation `recordId` and release its
41569
+ * coordinator state after its buffer activates. State owned by another generation
41570
+ * is left untouched.
41571
+ */
41572
+ static consumeReflectionBuffer(bufferKey, recordId) {
41573
+ const owner = BufferingCoordinator.reflectionBufferOwners.get(bufferKey);
41574
+ if (owner && owner.recordId !== recordId) return void 0;
41575
+ const cycleId = BufferingCoordinator.reflectionBufferCycleIds.get(bufferKey);
41576
+ if (owner && BufferingCoordinator.asyncBufferingOps.has(bufferKey)) owner.retired = true;
41577
+ else BufferingCoordinator.clearReflectionBuffer(bufferKey);
41578
+ return cycleId;
41579
+ }
41580
+ /** Called when the op that started as `owner` finishes; completes a deferred retirement. */
41581
+ static finishReflectionBuffer(bufferKey, owner) {
41582
+ if (BufferingCoordinator.reflectionBufferOwners.get(bufferKey) !== owner) return;
41583
+ if (owner.retired) BufferingCoordinator.clearReflectionBuffer(bufferKey);
41584
+ }
41501
41585
  constructor(opts) {
41502
41586
  this.observationConfig = opts.observationConfig;
41503
41587
  this.reflectionConfig = opts.reflectionConfig;
@@ -41553,6 +41637,7 @@ var BufferingCoordinator = class BufferingCoordinator {
41553
41637
  BufferingCoordinator.asyncBufferingOps.delete(obsBufKey);
41554
41638
  BufferingCoordinator.asyncBufferingOps.delete(reflBufKey);
41555
41639
  BufferingCoordinator.reflectionBufferCycleIds.delete(reflBufKey);
41640
+ BufferingCoordinator.reflectionBufferOwners.delete(reflBufKey);
41556
41641
  }
41557
41642
  }
41558
41643
  /**
@@ -41612,9 +41697,9 @@ const suggestedResponseInstructions = `Hint for the agent's immediate next messa
41612
41697
  - "The assistant should wait for the user to respond before continuing."
41613
41698
  - Call the view tool on src/example.ts to continue debugging.`;
41614
41699
  const threadTitleInstructions = `A short, noun-phrase title for this conversation (2-5 words). Examples:
41615
- - "Auth bug fix" — not "Fixing the auth bug"
41616
- - "Dark mode toggle" — not "User wants dark mode toggle added"
41617
- - "Deployment pipeline setup" — not "Setting up deployment pipeline for project"
41700
+ - "Auth bug fix" \u2014 not "Fixing the auth bug"
41701
+ - "Dark mode toggle" \u2014 not "User wants dark mode toggle added"
41702
+ - "Deployment pipeline setup" \u2014 not "Setting up deployment pipeline for project"
41618
41703
  Only update when the topic meaningfully changes.`;
41619
41704
  function createCurrentTaskExtractor() {
41620
41705
  return new Extractor({
@@ -42684,7 +42769,7 @@ var SyncObservationStrategy = class extends ObservationStrategy {
42684
42769
  failures: result.extractionFailures,
42685
42770
  previousValues: this.priorExtractedValues,
42686
42771
  rawObservations: result.observations,
42687
- recentMessages: formatMessagesForObserver(this.opts.messages, {
42772
+ recentMessages: () => formatMessagesForObserver(this.opts.messages, {
42688
42773
  maxPartLength: 500,
42689
42774
  timeZone: this.opts.record.observedTimezone
42690
42775
  }),
@@ -42908,7 +42993,7 @@ var AsyncBufferObservationStrategy = class extends ObservationStrategy {
42908
42993
  failures: result.extractionFailures,
42909
42994
  previousValues: this.priorExtractedValues,
42910
42995
  rawObservations: result.observations,
42911
- recentMessages: formatMessagesForObserver(messages, {
42996
+ recentMessages: () => formatMessagesForObserver(messages, {
42912
42997
  maxPartLength: 500,
42913
42998
  timeZone: this.opts.record.observedTimezone
42914
42999
  }),
@@ -43337,7 +43422,7 @@ var ResourceScopedObservationStrategy = class extends ObservationStrategy {
43337
43422
  failures: result.extractionFailures,
43338
43423
  previousValues,
43339
43424
  rawObservations: result.observations,
43340
- recentMessages: formatMessagesForObserver(threadMessages, {
43425
+ recentMessages: () => formatMessagesForObserver(threadMessages, {
43341
43426
  maxPartLength: 500,
43342
43427
  timeZone: this.opts.record.observedTimezone
43343
43428
  }),
@@ -43666,7 +43751,7 @@ var ObservationStep = class {
43666
43751
  }
43667
43752
  /** Step context from prepare(). Throws if prepare() hasn't been called. */
43668
43753
  get context() {
43669
- if (!this._context) throw new Error("Step not prepared yet — call prepare() first");
43754
+ if (!this._context) throw new Error("Step not prepared yet \u2014 call prepare() first");
43670
43755
  return this._context;
43671
43756
  }
43672
43757
  /**
@@ -44086,7 +44171,7 @@ var ObservationStep = class {
44086
44171
  const messagesToSeal = messageToSeal ? [messageToSeal] : [];
44087
44172
  this.turn.abortSignal?.throwIfAborted();
44088
44173
  om.sealMessagesForBuffering(messagesToSeal);
44089
- if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation — step-0 seeded response message holds the active id");
44174
+ if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation \u2014 step-0 seeded response message holds the active id");
44090
44175
  else try {
44091
44176
  await this.turn.hooks?.onSyncObservationComplete?.();
44092
44177
  } catch (error) {
@@ -44236,12 +44321,12 @@ var ObservationTurn = class {
44236
44321
  messageList;
44237
44322
  /** The current cached record. Refreshed after mutations (activate/observe/reflect). */
44238
44323
  get record() {
44239
- if (!this._record) throw new Error("Turn not started — call start() first");
44324
+ if (!this._record) throw new Error("Turn not started \u2014 call start() first");
44240
44325
  return this._record;
44241
44326
  }
44242
44327
  /** The context loaded during start(). */
44243
44328
  get context() {
44244
- if (!this._context) throw new Error("Turn not started — call start() first");
44329
+ if (!this._context) throw new Error("Turn not started \u2014 call start() first");
44245
44330
  return this._context;
44246
44331
  }
44247
44332
  /** Whether the turn has been ended and can no longer accept steps. */
@@ -44310,7 +44395,7 @@ var ObservationTurn = class {
44310
44395
  * (its output messages will be saved at the start of the new step's prepare()).
44311
44396
  */
44312
44397
  step(stepNumber) {
44313
- if (!this._started) throw new Error("Turn not started — call start() first");
44398
+ if (!this._started) throw new Error("Turn not started \u2014 call start() first");
44314
44399
  if (this._ended) throw new Error("Turn already ended");
44315
44400
  this._currentStep = new ObservationStep(this, stepNumber);
44316
44401
  return this._currentStep;
@@ -44405,6 +44490,79 @@ var ObservationTurn = class {
44405
44490
  };
44406
44491
  }
44407
44492
  };
44493
+ const pendingValuesBaseSchema = zod.z.object({
44494
+ recordId: zod.z.string(),
44495
+ reflectedObservationLineCount: zod.z.number(),
44496
+ values: zod.z.record(zod.z.string(), zod.z.unknown())
44497
+ });
44498
+ const pendingValuesSchema = zod.z.union([pendingValuesBaseSchema.extend({
44499
+ reflectionDigest: zod.z.string().regex(/^[a-f0-9]{64}$/),
44500
+ reflection: zod.z.never().optional()
44501
+ }), pendingValuesBaseSchema.extend({
44502
+ reflection: zod.z.string(),
44503
+ reflectionDigest: zod.z.never().optional()
44504
+ })]);
44505
+ const metadataSchema = zod.z.record(zod.z.string(), zod.z.unknown());
44506
+ function reflectionDigest(reflection) {
44507
+ return (0, crypto$1.createHash)("sha256").update(reflection).digest("hex");
44508
+ }
44509
+ function getMastraMetadata(metadata) {
44510
+ const parsed = metadataSchema.safeParse(metadata?.mastra);
44511
+ return parsed.success ? parsed.data : {};
44512
+ }
44513
+ /** Keep prepared values outside active OM metadata, durable across Memory instances. */
44514
+ async function stageBufferedReflectionValues(storage, record, values) {
44515
+ if (!record.threadId || !record.bufferedReflection) return;
44516
+ const digest = reflectionDigest(record.bufferedReflection);
44517
+ await storage.updateThreadMetadata({
44518
+ id: record.threadId,
44519
+ update: (thread) => ({
44520
+ ...thread.metadata,
44521
+ mastra: {
44522
+ ...getMastraMetadata(thread.metadata),
44523
+ omBufferedReflection: {
44524
+ recordId: record.id,
44525
+ reflectionDigest: digest,
44526
+ reflectedObservationLineCount: record.reflectedObservationLineCount ?? 0,
44527
+ values: values ?? {}
44528
+ }
44529
+ }
44530
+ })
44531
+ });
44532
+ }
44533
+ /** Called under the OM commit lock, only after this exact buffer was activated. */
44534
+ async function publishBufferedReflectionValues(storage, extractors, record) {
44535
+ if (!record.threadId || !record.bufferedReflection) return;
44536
+ const digest = reflectionDigest(record.bufferedReflection);
44537
+ await storage.updateThreadMetadata({
44538
+ id: record.threadId,
44539
+ update: (thread) => {
44540
+ const mastra = getMastraMetadata(thread.metadata);
44541
+ const parsed = pendingValuesSchema.safeParse(mastra.omBufferedReflection);
44542
+ if (!parsed.success) return;
44543
+ const pending = parsed.data;
44544
+ if (pending.recordId !== record.id || (pending.reflectionDigest !== void 0 ? pending.reflectionDigest !== digest : pending.reflection !== record.bufferedReflection) || pending.reflectedObservationLineCount !== (record.reflectedObservationLineCount ?? 0)) return;
44545
+ const update = buildThreadMetadataFromExtractedValues(extractors, pending.values);
44546
+ const previous = (0, _mastra_core_memory.getThreadOMMetadata)(thread.metadata);
44547
+ const metadata = (0, _mastra_core_memory.setThreadOMMetadata)(thread.metadata, {
44548
+ currentTask: update.currentTask ?? previous?.currentTask,
44549
+ suggestedResponse: update.suggestedResponse ?? previous?.suggestedResponse,
44550
+ threadTitle: update.threadTitle ?? previous?.threadTitle,
44551
+ extracted: {
44552
+ ...previous?.extracted,
44553
+ ...update.extracted
44554
+ }
44555
+ });
44556
+ return {
44557
+ ...metadata,
44558
+ mastra: {
44559
+ ...getMastraMetadata(metadata),
44560
+ omBufferedReflection: null
44561
+ }
44562
+ };
44563
+ }
44564
+ });
44565
+ }
44408
44566
  /**
44409
44567
  * Build the Reflector's system prompt.
44410
44568
  *
@@ -44458,8 +44616,8 @@ When consolidating observations:
44458
44616
  - 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
44459
44617
  - Prefer many short factual lines over prose summaries. Do not replace facts with generalities like "discussed travel plans"
44460
44618
  - Combine related items where it makes sense (e.g., "agent called view tool 5 times on file x")
44461
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44462
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
44619
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44620
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
44463
44621
  - Condense the wording of older observations more than recent ones, but keep their facts
44464
44622
 
44465
44623
  CRITICAL: USER ASSERTIONS vs QUESTIONS
@@ -44481,23 +44639,23 @@ When observations contain <thread id="..."> sections:
44481
44639
  Example input:
44482
44640
  <thread id="thread-1">
44483
44641
  Date: Dec 4, 2025
44484
- * 🔴 (14:30) User prefers TypeScript
44485
- * 🟡 (14:35) Working on auth feature
44642
+ * \u{1F534} (14:30) User prefers TypeScript
44643
+ * \u{1F7E1} (14:35) Working on auth feature
44486
44644
  </thread>
44487
44645
  <thread id="thread-2">
44488
44646
  Date: Dec 4, 2025
44489
- * 🔴 (15:00) User prefers TypeScript
44490
- * 🟡 (15:05) Debugging API endpoint
44647
+ * \u{1F534} (15:00) User prefers TypeScript
44648
+ * \u{1F7E1} (15:05) Debugging API endpoint
44491
44649
  </thread>
44492
44650
 
44493
44651
  Example output (consolidated):
44494
44652
  Date: Dec 4, 2025
44495
- * 🔴 (14:30) User prefers TypeScript
44653
+ * \u{1F534} (14:30) User prefers TypeScript
44496
44654
  <thread id="thread-1">
44497
- * 🟡 (14:35) Working on auth feature
44655
+ * \u{1F7E1} (14:35) Working on auth feature
44498
44656
  </thread>
44499
44657
  <thread id="thread-2">
44500
- * 🟡 (15:05) Debugging API endpoint
44658
+ * \u{1F7E1} (15:05) Debugging API endpoint
44501
44659
  </thread>
44502
44660
 
44503
44661
  === OUTPUT FORMAT ===
@@ -44528,8 +44686,8 @@ Please re-process with slightly more compression:
44528
44686
  - Memory is getting long - use a more condensed style throughout
44529
44687
  - Combine related items more aggressively but do not lose important specific details of names, places, events, and people
44530
44688
  - 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
44531
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44532
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
44689
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44690
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
44533
44691
 
44534
44692
  Aim for a 8/10 detail level.
44535
44693
  `,
@@ -44545,8 +44703,8 @@ Please re-process with much more aggressive compression:
44545
44703
  - Combine related items aggressively but do not lose important specific details of names, places, events, and people
44546
44704
  - 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
44547
44705
  - If the same file or module is mentioned across many observations, merge into one entry covering the full arc
44548
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44549
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
44706
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44707
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
44550
44708
  - Remove redundant information and merge overlapping observations
44551
44709
 
44552
44710
  Aim for a 6/10 detail level.
@@ -44557,14 +44715,14 @@ Aim for a 6/10 detail level.
44557
44715
  Your previous reflections have failed to compress sufficiently after multiple attempts.
44558
44716
 
44559
44717
  Please re-process with maximum compression:
44560
- - Summarize the oldest observations (first 50-70%) into brief high-level paragraphs — only key facts, decisions, and outcomes
44718
+ - Summarize the oldest observations (first 50-70%) into brief high-level paragraphs \u2014 only key facts, decisions, and outcomes
44561
44719
  - For the most recent observations (last 30-50%), retain important details but still use a condensed style
44562
- - Ruthlessly merge related observations — if 10 observations are about the same topic, combine into 1-2 lines
44563
- - Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries — drop individual steps entirely
44564
- - Drop procedural details (tool calls, retries, intermediate steps) — keep only final outcomes
44720
+ - Ruthlessly merge related observations \u2014 if 10 observations are about the same topic, combine into 1-2 lines
44721
+ - Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries \u2014 drop individual steps entirely
44722
+ - Drop procedural details (tool calls, retries, intermediate steps) \u2014 keep only final outcomes
44565
44723
  - Drop observations that are no longer relevant or have been superseded by newer information
44566
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44567
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
44724
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44725
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
44568
44726
  - Preserve: names, dates, decisions, errors, user preferences, and architectural choices
44569
44727
 
44570
44728
  Aim for a 4/10 detail level.
@@ -44575,14 +44733,14 @@ Aim for a 4/10 detail level.
44575
44733
  Multiple compression attempts have failed. The content may already be dense from a prior reflection.
44576
44734
 
44577
44735
  You MUST dramatically reduce the number of observations while keeping the standard observation format (date groups with bullet points and priority emojis):
44578
- - 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")
44579
- - Never preserve individual tool calls (viewed file X, searched for Y, ran build) — only preserve what was discovered or accomplished
44736
+ - 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")
44737
+ - Never preserve individual tool calls (viewed file X, searched for Y, ran build) \u2014 only preserve what was discovered or accomplished
44580
44738
  - Consolidate many related observations into single, more generic observations
44581
44739
  - Merge all same-day date groups into at most 2-3 date groups per day
44582
44740
  - For older content, each topic or task should be at most 1-2 observations capturing the key outcome
44583
44741
  - For recent content, retain more detail but still merge related items aggressively
44584
44742
  - If multiple observations describe incremental progress on the same task, keep only the final state
44585
- - Preserve ✅ completion markers and their outcomes but merge related completions into fewer lines
44743
+ - Preserve \u2705 completion markers and their outcomes but merge related completions into fewer lines
44586
44744
  - Preserve: user preferences, key decisions, architectural choices, and unresolved issues
44587
44745
 
44588
44746
  Aim for a 2/10 detail level. Fewer, more generic observations are better than many specific ones that exceed the budget.
@@ -44762,6 +44920,15 @@ function isReflectionApplied(returned, newRecordId, reflectedRecordId) {
44762
44920
  return returned.supersededBy === void 0 && returned.id !== reflectedRecordId;
44763
44921
  }
44764
44922
  /**
44923
+ * The active observations a buffered-reflection swap writes: the buffered reflection replaces the
44924
+ * first `reflectedLineCount` lines, and the trimmed remainder follows after a blank line. Mirrors
44925
+ * `swapBufferedReflectionToActive` in the storage adapters.
44926
+ */
44927
+ function bufferedActivationText({ bufferedReflection, observations, reflectedLineCount }) {
44928
+ const unreflected = observations.split("\n").slice(reflectedLineCount).join("\n").trim();
44929
+ return unreflected ? `${bufferedReflection}\n\n${unreflected}` : bufferedReflection;
44930
+ }
44931
+ /**
44765
44932
  * Runs the Reflector agent for compressing observations.
44766
44933
  * Handles synchronous reflection, async buffered reflection, and activation.
44767
44934
  */
@@ -44996,7 +45163,7 @@ var ReflectorRunner = class {
44996
45163
  operationType: "reflection",
44997
45164
  startedAt: streamContext.startedAt,
44998
45165
  tokensAttempted: originalTokens,
44999
- error: `Did not compress below threshold (${originalTokens} → ${reflectedTokens}, target: ${targetThreshold}), retrying at level ${currentLevel + 1}`,
45166
+ error: `Did not compress below threshold (${originalTokens} \u2192 ${reflectedTokens}, target: ${targetThreshold}), retrying at level ${currentLevel + 1}`,
45000
45167
  retrying: true,
45001
45168
  recordId: streamContext.recordId,
45002
45169
  threadId: streamContext.threadId
@@ -45026,7 +45193,7 @@ var ReflectorRunner = class {
45026
45193
  }
45027
45194
  currentLevel = Math.min(currentLevel + 1, maxLevel);
45028
45195
  }
45029
- 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`);
45196
+ 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`);
45030
45197
  const structuredExtraction = await extractStructuredValues({
45031
45198
  agent,
45032
45199
  source: "reflector",
@@ -45070,18 +45237,18 @@ var ReflectorRunner = class {
45070
45237
  startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel) {
45071
45238
  const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
45072
45239
  if (this.buffering.isAsyncBufferingInProgress(bufferKey)) return;
45073
- BufferingCoordinator.lastBufferedBoundary.set(bufferKey, observationTokens);
45240
+ const owner = BufferingCoordinator.startReflectionBuffer(bufferKey, observationTokens, record.id);
45074
45241
  registerOp(record.id, "bufferingReflection");
45075
45242
  const flagSet = this.storage.setBufferingReflectionFlag(record.id, true).catch((err) => {
45076
45243
  omError("[OM] Failed to set buffering reflection flag", err);
45077
45244
  });
45078
- const asyncOp = (async () => {
45245
+ const run = async () => {
45079
45246
  await flagSet;
45080
45247
  let outcome;
45081
45248
  let reflectionError;
45082
45249
  try {
45083
45250
  await reflectionHooks?.onReflectionStart?.();
45084
- outcome = await this.doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
45251
+ outcome = await this.doAsyncBufferedReflection(record, bufferKey, owner, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
45085
45252
  } catch (error) {
45086
45253
  reflectionError = error instanceof Error ? error : new Error(String(error));
45087
45254
  if (writer) try {
@@ -45104,7 +45271,7 @@ var ReflectorRunner = class {
45104
45271
  omError("[OM] Failed to persist buffering-failed marker after async buffered reflection failure", markerError);
45105
45272
  }
45106
45273
  omError("[OM] Async buffered reflection failed", error);
45107
- BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
45274
+ owner.retired = true;
45108
45275
  } finally {
45109
45276
  try {
45110
45277
  await reflectionHooks?.onReflectionEnd?.({
@@ -45115,13 +45282,15 @@ var ReflectorRunner = class {
45115
45282
  } catch (hookError) {
45116
45283
  omError("[OM] onReflectionEnd hook failed after async buffered reflection", hookError);
45117
45284
  }
45118
- BufferingCoordinator.asyncBufferingOps.delete(bufferKey);
45285
+ BufferingCoordinator.finishReflectionBuffer(bufferKey, owner);
45286
+ if (BufferingCoordinator.asyncBufferingOps.get(bufferKey) === asyncOp) BufferingCoordinator.asyncBufferingOps.delete(bufferKey);
45119
45287
  unregisterOp(record.id, "bufferingReflection");
45120
45288
  await this.storage.setBufferingReflectionFlag(record.id, false).catch((err) => {
45121
45289
  omError("[OM] Failed to clear buffering reflection flag", err);
45122
45290
  });
45123
45291
  }
45124
- })();
45292
+ };
45293
+ const asyncOp = run();
45125
45294
  BufferingCoordinator.asyncBufferingOps.set(bufferKey, asyncOp);
45126
45295
  this.trackBackgroundWork?.(asyncOp, lockKey);
45127
45296
  }
@@ -45129,13 +45298,27 @@ var ReflectorRunner = class {
45129
45298
  * Perform async buffered reflection — reflects observations and stores to bufferedReflection.
45130
45299
  * Does NOT create a new generation or update activeObservations.
45131
45300
  */
45132
- async doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel) {
45133
- const currentRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId) ?? record;
45301
+ async doAsyncBufferedReflection(record, bufferKey, owner, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel) {
45302
+ const freshRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
45303
+ if (BufferingCoordinator.reflectionBufferOwners.get(bufferKey) !== owner) {
45304
+ omDebug(`[OM:reflect] doAsyncBufferedReflection: ${bufferKey} was cleared while the op waited; stopping`);
45305
+ return;
45306
+ }
45307
+ const currentRecord = freshRecord ?? record;
45308
+ if (freshRecord?.bufferedReflection) {
45309
+ omDebug(`[OM:reflect] doAsyncBufferedReflection: live head ${freshRecord.id} already has a buffered reflection; skipping duplicate run`);
45310
+ owner.retired = true;
45311
+ return;
45312
+ }
45134
45313
  const observationTokens = currentRecord.observationTokenCount ?? 0;
45135
45314
  const reflectThreshold = getMaxThreshold(this.getEffectiveReflectionTokens(currentRecord));
45136
45315
  const bufferActivation = this.reflectionConfig.bufferActivation ?? .5;
45137
45316
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
45138
45317
  const cycleId = `reflect-buf-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
45318
+ if (owner.recordId !== currentRecord.id) {
45319
+ owner.recordId = currentRecord.id;
45320
+ owner.retired = false;
45321
+ }
45139
45322
  BufferingCoordinator.reflectionBufferCycleIds.set(bufferKey, cycleId);
45140
45323
  const allLines = (currentRecord.activeObservations ?? "").split("\n");
45141
45324
  const totalLines = allLines.length;
@@ -45151,7 +45334,7 @@ var ReflectorRunner = class {
45151
45334
  const reflectedObservationLineCount = linesToReflect;
45152
45335
  const sliceTokenEstimate = Math.round(avgTokensPerLine * linesToReflect);
45153
45336
  const compressionTarget = Math.round(sliceTokenEstimate * .75);
45154
- omDebug(`[OM:reflect] doAsyncBufferedReflection: slicing observations for reflection — totalLines=${totalLines}, avgTokPerLine=${avgTokensPerLine.toFixed(1)}, activationPointTokens=${activationPointTokens}, linesToReflect=${linesToReflect}/${totalLines}, sliceTokenEstimate=${sliceTokenEstimate}, compressionTarget=${compressionTarget}`);
45337
+ omDebug(`[OM:reflect] doAsyncBufferedReflection: slicing observations for reflection \u2014 totalLines=${totalLines}, avgTokPerLine=${avgTokensPerLine.toFixed(1)}, activationPointTokens=${activationPointTokens}, linesToReflect=${linesToReflect}/${totalLines}, sliceTokenEstimate=${sliceTokenEstimate}, compressionTarget=${compressionTarget}`);
45155
45338
  omDebug(`[OM:reflect] doAsyncBufferedReflection: starting reflector call, recordId=${currentRecord.id}, observationTokens=${sliceTokenEstimate}, compressionTarget=${compressionTarget} (inputTokens), activeObsLength=${activeObservations.length}, reflectedLineCount=${reflectedObservationLineCount}`);
45156
45339
  if (writer) {
45157
45340
  const startMarker = createBufferingStartMarker({
@@ -45172,10 +45355,18 @@ var ReflectorRunner = class {
45172
45355
  const compressionStartLevel = await this.getCompressionStartLevel(requestContext);
45173
45356
  const reflectResult = await this.call(activeObservations, void 0, void 0, compressionTarget, void 0, true, compressionStartLevel, requestContext, priorExtractedValues, observabilityContext, void 0, mainAgent, sendSignal, currentModel);
45174
45357
  reflectResult.observations = await applyTextTransform(this.hooks, "afterReflection", reflectResult.observations, hookContext);
45358
+ if (!reflectResult.observations.trim()) {
45359
+ omDebug(`[OM:reflect] doAsyncBufferedReflection: reflection for ${currentRecord.id} is empty after afterReflection; discarding it`);
45360
+ owner.retired = true;
45361
+ return {
45362
+ usage: reflectResult.usage,
45363
+ providerMetadata: reflectResult.providerMetadata
45364
+ };
45365
+ }
45175
45366
  const reflectionTokenCount = this.tokenCounter.countObservations(reflectResult.observations);
45176
45367
  omDebug(`[OM:reflect] doAsyncBufferedReflection: reflector returned ${reflectionTokenCount} tokens (${reflectResult.observations?.length} chars), saving to recordId=${currentRecord.id}`);
45177
45368
  if (!await runOMCommit(this.buffering.getLockKey(currentRecord.threadId, currentRecord.resourceId), async () => {
45178
- if ((await this.storage.getObservationalMemory(currentRecord.threadId, currentRecord.resourceId))?.id !== currentRecord.id) return false;
45369
+ if ((await this.storage.getObservationalMemory(currentRecord.threadId, currentRecord.resourceId))?.id !== currentRecord.id || BufferingCoordinator.reflectionBufferOwners.get(bufferKey) !== owner) return false;
45179
45370
  await this.storage.updateBufferedReflection({
45180
45371
  id: currentRecord.id,
45181
45372
  reflection: reflectResult.observations,
@@ -45183,17 +45374,18 @@ var ReflectorRunner = class {
45183
45374
  inputTokenCount: sliceTokenEstimate,
45184
45375
  reflectedObservationLineCount
45185
45376
  });
45377
+ const buffered = await this.storage.getObservationalMemory(currentRecord.threadId, currentRecord.resourceId);
45378
+ if (buffered?.id === currentRecord.id && buffered.bufferedReflection === reflectResult.observations) await stageBufferedReflectionValues(this.storage, buffered, reflectResult.extractedValues);
45186
45379
  return true;
45187
45380
  })) {
45188
45381
  omDebug(`[OM:reflect] doAsyncBufferedReflection: record ${currentRecord.id} is no longer the head; discarding the buffered reflection`);
45189
- BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
45382
+ owner.retired = true;
45190
45383
  return {
45191
45384
  usage: reflectResult.usage,
45192
45385
  providerMetadata: reflectResult.providerMetadata
45193
45386
  };
45194
45387
  }
45195
45388
  omDebug(`[OM:reflect] doAsyncBufferedReflection: bufferedReflection saved with lineCount=${reflectedObservationLineCount}`);
45196
- await persistThreadExtractedValues(this.storage, this.reflectionConfig.extractors, currentRecord.threadId ?? void 0, reflectResult.extractedValues);
45197
45389
  if (writer) {
45198
45390
  const endMarker = createBufferingEndMarker({
45199
45391
  cycleId,
@@ -45219,6 +45411,57 @@ var ReflectorRunner = class {
45219
45411
  };
45220
45412
  }
45221
45413
  /**
45414
+ * Decide what a buffered-reflection swap did. Built-in adapters only swap the buffer and line
45415
+ * count in the snapshot, return the stored record (no new generation) when another writer
45416
+ * extended them after the head check, and mark a generation they created after that check with
45417
+ * `bufferedReflectionVerified`. Adapters without that check build the new generation from
45418
+ * whatever is stored. Either way the swap must also produce what the snapshot's buffer and line
45419
+ * count give from the text the swap retired (retired records are never written again, so that
45420
+ * text is exactly what the swap read).
45421
+ *
45422
+ * Staged values are published only with the adapter's proof. Without it an extension that
45423
+ * repeats the unreflected tail produces the same text as the snapshot's buffer, so the values
45424
+ * fail closed: the activation still applies, but the staged values stay unpublished.
45425
+ */
45426
+ async classifyBufferedReflectionSwap({ result, newRecordId, snapshot, bufferedReflection, reflectedLineCount }) {
45427
+ if (result.id === snapshot.id) return {
45428
+ kind: "not-applied",
45429
+ headId: result.id
45430
+ };
45431
+ const createdByThisSwap = result.id === newRecordId;
45432
+ if (!createdByThisSwap && result.supersededBy !== void 0) return {
45433
+ kind: "not-applied",
45434
+ headId: result.id
45435
+ };
45436
+ const swapActiveObservations = result.activeObservations;
45437
+ const bufferedReflectionVerified = result.bufferedReflectionVerified === true;
45438
+ let matchesSnapshotBuffer = false;
45439
+ try {
45440
+ const retired = (await this.storage.getObservationalMemoryHistory(snapshot.threadId, snapshot.resourceId, 5, { recordId: snapshot.id })).find((candidate) => candidate.id === snapshot.id);
45441
+ matchesSnapshotBuffer = retired !== void 0 && swapActiveObservations === bufferedActivationText({
45442
+ bufferedReflection,
45443
+ observations: retired.activeObservations,
45444
+ reflectedLineCount
45445
+ });
45446
+ } catch (error) {
45447
+ omError("[OM] Failed to read the generation retired by buffered reflection activation", error);
45448
+ }
45449
+ const snapshotBufferActivated = matchesSnapshotBuffer && bufferedReflectionVerified;
45450
+ if (createdByThisSwap) return {
45451
+ kind: "applied",
45452
+ record: result,
45453
+ snapshotBufferActivated
45454
+ };
45455
+ return matchesSnapshotBuffer ? {
45456
+ kind: "applied",
45457
+ record: result,
45458
+ snapshotBufferActivated
45459
+ } : {
45460
+ kind: "not-applied",
45461
+ headId: result.id
45462
+ };
45463
+ }
45464
+ /**
45222
45465
  * Try to activate buffered reflection when threshold is reached.
45223
45466
  * Returns a discriminated result so the caller can distinguish between
45224
45467
  * "activated", "no buffer present", and "suppressed by overshoot guard"
@@ -45238,24 +45481,32 @@ var ReflectorRunner = class {
45238
45481
  }
45239
45482
  }
45240
45483
  }
45241
- const freshRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
45484
+ const storedRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
45485
+ const freshRecord = storedRecord ? { ...storedRecord } : void 0;
45242
45486
  omDebug(`[OM:reflect] tryActivateBufferedReflection: recordId=${record.id}, hasBufferedReflection=${!!freshRecord?.bufferedReflection}, bufferedReflectionLen=${freshRecord?.bufferedReflection?.length ?? 0}`);
45243
45487
  omDebug(`[OM:reflect] tryActivateBufferedReflection: freshRecord.id=${freshRecord?.id}, freshBufferedReflection=${freshRecord?.bufferedReflection ? "present (" + freshRecord.bufferedReflection.length + " chars)" : "empty"}, freshObsTokens=${freshRecord?.observationTokenCount}`);
45488
+ if (freshRecord) await BufferingCoordinator.reconcileReflectionBufferHead(bufferKey, freshRecord.id, () => this.storage.getObservationalMemory(record.threadId, record.resourceId));
45244
45489
  if (!freshRecord?.bufferedReflection) {
45245
45490
  omDebug(`[OM:reflect] tryActivateBufferedReflection: no buffered reflection after re-fetch`);
45246
45491
  return { status: "no-buffer" };
45247
45492
  }
45248
45493
  const beforeTokens = freshRecord.observationTokenCount ?? 0;
45249
45494
  const reflectedLineCount = freshRecord.reflectedObservationLineCount ?? 0;
45250
- const unreflectedLines = (freshRecord.activeObservations ?? "").split("\n").slice(reflectedLineCount);
45495
+ const currentObservations = freshRecord.activeObservations ?? "";
45496
+ const unreflectedLines = currentObservations.split("\n").slice(reflectedLineCount);
45251
45497
  const unreflectedContent = unreflectedLines.join("\n").trim();
45252
- const combinedObservations = unreflectedContent ? `${freshRecord.bufferedReflection}\n\n${unreflectedContent}` : freshRecord.bufferedReflection;
45498
+ const bufferedReflection = freshRecord.bufferedReflection;
45499
+ const combinedObservations = bufferedActivationText({
45500
+ bufferedReflection,
45501
+ observations: currentObservations,
45502
+ reflectedLineCount
45503
+ });
45253
45504
  const combinedTokenCount = this.tokenCounter.countObservations(combinedObservations);
45254
45505
  if (activationMetadata?.triggeredBy === "ttl" || activationMetadata?.triggeredBy === "provider_change") {
45255
45506
  const unreflectedTailTokens = unreflectedContent ? this.tokenCounter.countObservations(unreflectedContent) : 0;
45256
45507
  const bufferedReflectionTokens = freshRecord.bufferedReflectionTokens ?? 0;
45257
45508
  if (unreflectedTailTokens < bufferedReflectionTokens) {
45258
- omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation — unreflectedTailTokens=${unreflectedTailTokens} < bufferedReflectionTokens=${bufferedReflectionTokens}; keeping buffer for threshold activation`);
45509
+ omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation \u2014 unreflectedTailTokens=${unreflectedTailTokens} < bufferedReflectionTokens=${bufferedReflectionTokens}; keeping buffer for threshold activation`);
45259
45510
  return {
45260
45511
  status: "suppressed",
45261
45512
  reason: "composition"
@@ -45266,7 +45517,7 @@ var ReflectorRunner = class {
45266
45517
  const regularActivationTarget = reflectThreshold * (1 - bufferActivation);
45267
45518
  const minCombinedTokens = Math.round(regularActivationTarget * EARLY_ACTIVATION_SIZE_FLOOR_RATIO);
45268
45519
  if (combinedTokenCount < minCombinedTokens) {
45269
- 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`);
45520
+ 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`);
45270
45521
  return {
45271
45522
  status: "suppressed",
45272
45523
  reason: "size"
@@ -45275,28 +45526,48 @@ var ReflectorRunner = class {
45275
45526
  }
45276
45527
  omDebug(`[OM:reflect] tryActivateBufferedReflection: activating, beforeTokens=${beforeTokens}, combinedTokenCount=${combinedTokenCount}, reflectedLineCount=${reflectedLineCount}, unreflectedLines=${unreflectedLines.length}`);
45277
45528
  const newRecordId = crypto.randomUUID();
45278
- const swapped = await runOMCommit(lockKey, () => {
45529
+ const commit = await runOMCommit(lockKey, async () => {
45279
45530
  abortSignal?.throwIfAborted();
45280
- return this.storage.swapBufferedReflectionToActive({
45531
+ const head = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
45532
+ if (head && (head.id !== freshRecord.id || head.bufferedReflection !== freshRecord.bufferedReflection || head.reflectedObservationLineCount !== freshRecord.reflectedObservationLineCount)) return {
45533
+ kind: "not-applied",
45534
+ headId: head.id
45535
+ };
45536
+ const result = await this.storage.swapBufferedReflectionToActive({
45281
45537
  currentRecord: freshRecord,
45282
45538
  tokenCount: combinedTokenCount,
45283
45539
  newRecordId
45284
45540
  });
45541
+ const outcome = await this.classifyBufferedReflectionSwap({
45542
+ result,
45543
+ newRecordId,
45544
+ snapshot: freshRecord,
45545
+ bufferedReflection,
45546
+ reflectedLineCount
45547
+ });
45548
+ if (outcome.kind === "applied" && outcome.snapshotBufferActivated) try {
45549
+ await publishBufferedReflectionValues(this.storage, this.reflectionConfig.extractors, freshRecord);
45550
+ } catch (error) {
45551
+ omError("[OM] Failed to publish buffered reflection values after activation", error);
45552
+ }
45553
+ return outcome;
45285
45554
  }, {
45286
45555
  priority: "reflection",
45287
45556
  abortSignal
45288
45557
  });
45289
- if (!isReflectionApplied(swapped, newRecordId, freshRecord.id)) {
45290
- omDebug(`[OM:reflect] tryActivateBufferedReflection: buffered reflection on ${freshRecord.id} not applied (head is ${swapped.id})`);
45558
+ if (commit.kind === "not-applied") {
45559
+ omDebug(`[OM:reflect] tryActivateBufferedReflection: buffered reflection on ${freshRecord.id} not applied (head is ${commit.headId})`);
45560
+ if (commit.headId !== freshRecord.id) BufferingCoordinator.retireReflectionBuffer(bufferKey, freshRecord.id);
45291
45561
  return { status: "not-applied" };
45292
45562
  }
45293
- BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
45563
+ if (!commit.snapshotBufferActivated) omDebug(`[OM:reflect] tryActivateBufferedReflection: ${commit.record.id} does not hold exactly the snapshot's buffered reflection (extended by another writer, or unverifiable); staged values stay unpublished`);
45564
+ const originalCycleId = BufferingCoordinator.consumeReflectionBuffer(bufferKey, freshRecord.id);
45294
45565
  const afterRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
45295
45566
  const afterTokens = afterRecord?.observationTokenCount ?? 0;
45296
45567
  omDebug(`[OM:reflect] tryActivateBufferedReflection: activation complete! beforeTokens=${beforeTokens}, afterTokens=${afterTokens}, newRecordId=${afterRecord?.id}, newGenCount=${afterRecord?.generationCount}`);
45297
45568
  if (writer) {
45298
45569
  const activationMarker = createActivationMarker({
45299
- cycleId: BufferingCoordinator.reflectionBufferCycleIds.get(bufferKey) ?? `reflect-act-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
45570
+ cycleId: originalCycleId ?? `reflect-act-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
45300
45571
  operationType: "reflection",
45301
45572
  chunksActivated: 1,
45302
45573
  tokensActivated: beforeTokens,
@@ -45322,7 +45593,6 @@ var ReflectorRunner = class {
45322
45593
  }).catch(() => {});
45323
45594
  await this.persistMarkerToMessage(activationMarker, messageList, freshRecord.threadId ?? "", freshRecord.resourceId ?? void 0, abortSignal);
45324
45595
  }
45325
- BufferingCoordinator.reflectionBufferCycleIds.delete(bufferKey);
45326
45596
  return { status: "activated" };
45327
45597
  }
45328
45598
  /**
@@ -45339,7 +45609,7 @@ var ReflectorRunner = class {
45339
45609
  const priorExtractedValues = await getThreadExtractedValues(this.storage, this.reflectionConfig.extractors, requestedThreadId ?? record.threadId);
45340
45610
  abortSignal?.throwIfAborted();
45341
45611
  if (this.buffering.isAsyncReflectionEnabled() && observationTokens < reflectThreshold) {
45342
- if ((() => {
45612
+ if (await (async () => {
45343
45613
  if (!this.buffering.isAsyncReflectionEnabled()) return false;
45344
45614
  if (record.isBufferingReflection) {
45345
45615
  if (isOpActiveInProcess(record.id, "bufferingReflection")) return false;
@@ -45347,6 +45617,7 @@ var ReflectorRunner = class {
45347
45617
  this.storage.setBufferingReflectionFlag(record.id, false).catch(() => {});
45348
45618
  }
45349
45619
  const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
45620
+ await BufferingCoordinator.reconcileReflectionBufferHead(bufferKey, record.id, () => this.storage.getObservationalMemory(record.threadId, record.resourceId));
45350
45621
  if (this.buffering.isAsyncBufferingInProgress(bufferKey)) return false;
45351
45622
  if (BufferingCoordinator.lastBufferedBoundary.has(bufferKey)) return false;
45352
45623
  if (record.bufferedReflection) return false;
@@ -45375,7 +45646,7 @@ var ReflectorRunner = class {
45375
45646
  omDebug(`[OM:reflect] isReflecting=true and active in this process, skipping`);
45376
45647
  return;
45377
45648
  }
45378
- omDebug(`[OM:reflect] isReflecting=true but NOT active in this process — stale flag from dead process, clearing`);
45649
+ omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
45379
45650
  await this.storage.setReflectingFlag(record.id, false);
45380
45651
  }
45381
45652
  if (this.buffering.isAsyncReflectionEnabled()) {
@@ -45389,10 +45660,15 @@ var ReflectorRunner = class {
45389
45660
  else {
45390
45661
  const activationPoint = reflectThreshold * this.reflectionConfig.bufferActivation;
45391
45662
  if (observationTokens < activationPoint) {
45392
- omDebug(`[OM:reflect] skipping async reflection — observationTokens (${observationTokens}) below activation point (${activationPoint}), triggered by ${activationTriggeredBy}`);
45663
+ omDebug(`[OM:reflect] skipping async reflection \u2014 observationTokens (${observationTokens}) below activation point (${activationPoint}), triggered by ${activationTriggeredBy}`);
45664
+ return;
45665
+ }
45666
+ const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
45667
+ if (this.buffering.isAsyncBufferingInProgress(bufferKey) || BufferingCoordinator.lastBufferedBoundary.has(bufferKey)) {
45668
+ omDebug(`[OM:reflect] skipping async reflection \u2014 reflection buffer already active or present for ${bufferKey}`);
45393
45669
  return;
45394
45670
  }
45395
- omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) — starting background reflection`);
45671
+ omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) \u2014 starting background reflection`);
45396
45672
  this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
45397
45673
  return;
45398
45674
  }
@@ -45400,7 +45676,7 @@ var ReflectorRunner = class {
45400
45676
  if (activationTriggeredBy === "threshold") {
45401
45677
  const suppressedAtTokens = this.syncReflectionSuppression.get(lockKey);
45402
45678
  if (suppressedAtTokens !== void 0 && observationTokens === suppressedAtTokens) {
45403
- omDebug(`[OM:reflect] skipping sync reflection — observations unchanged at ${observationTokens} tokens since the last unproductive attempt; retrying once they change`);
45679
+ omDebug(`[OM:reflect] skipping sync reflection \u2014 observations unchanged at ${observationTokens} tokens since the last unproductive attempt; retrying once they change`);
45404
45680
  return;
45405
45681
  }
45406
45682
  }
@@ -46241,7 +46517,7 @@ var ObservationalMemory = class ObservationalMemory {
46241
46517
  const asyncBufferingDisabled = config.observation?.bufferTokens === false || config.scope === "resource" && !userExplicitlyConfiguredAsync;
46242
46518
  if (isSharedBudget && !asyncBufferingDisabled) {
46243
46519
  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).");
46244
- 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.");
46520
+ 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.");
46245
46521
  }
46246
46522
  const observationActivateAfterIdle = config.observation?.activateAfterIdle ?? config.activateAfterIdle;
46247
46523
  const observationActivateAfterIdlePath = config.observation?.activateAfterIdle !== void 0 ? "observation.activateAfterIdle" : "activateAfterIdle";
@@ -46338,7 +46614,7 @@ var ObservationalMemory = class ObservationalMemory {
46338
46614
  hasWarnedResourceScopeDeprecation = true;
46339
46615
  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");
46340
46616
  }
46341
- 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}`);
46617
+ 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}`);
46342
46618
  }
46343
46619
  __registerMastra(mastra) {
46344
46620
  this.mastra = mastra;
@@ -46619,7 +46895,7 @@ var ObservationalMemory = class ObservationalMemory {
46619
46895
  threadId: null,
46620
46896
  resourceId: resourceId ?? threadId
46621
46897
  };
46622
- 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.");
46898
+ 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.");
46623
46899
  return {
46624
46900
  threadId,
46625
46901
  resourceId: resourceId ?? threadId
@@ -46930,7 +47206,7 @@ var ObservationalMemory = class ObservationalMemory {
46930
47206
  const isImportant = new Array(totalCount);
46931
47207
  for (let i = 0; i < totalCount; i++) {
46932
47208
  lineTokens[i] = this.tokenCounter.countString(lines[i]);
46933
- isImportant[i] = lines[i].includes("🔴") || lines[i].includes("✅");
47209
+ isImportant[i] = lines[i].includes("\u{1F534}") || lines[i].includes("\u2705");
46934
47210
  }
46935
47211
  const suffixTokens = new Array(totalCount + 1);
46936
47212
  suffixTokens[totalCount] = 0;
@@ -47263,7 +47539,7 @@ ${formattedMessages}
47263
47539
  resourceId: freshRecord.resourceId ?? void 0
47264
47540
  });
47265
47541
  } catch (err) {
47266
- omError("[OM] Failed to persist sealed messages before buffering — skipping observation cycle", err);
47542
+ omError("[OM] Failed to persist sealed messages before buffering \u2014 skipping observation cycle", err);
47267
47543
  return;
47268
47544
  }
47269
47545
  const cycleId = `buffer-obs-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
@@ -48413,7 +48689,7 @@ ${formattedMessages}
48413
48689
  usage: void 0
48414
48690
  };
48415
48691
  }
48416
- omDebug(`[OM:reflect] isReflecting=true but NOT active in this process — stale flag from dead process, clearing`);
48692
+ omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
48417
48693
  await this.storage.setReflectingFlag(record.id, false);
48418
48694
  }
48419
48695
  await this.storage.setReflectingFlag(record.id, true);
@@ -48647,7 +48923,7 @@ ${formattedMessages}
48647
48923
  };
48648
48924
  const TEMPORAL_GAP_REMINDER_TYPE = "temporal-gap";
48649
48925
  function getTemporalGapReminderText(gapText, timestamp) {
48650
- return `${gapText} — ${formatTemporalTimestamp(new Date(timestamp))}`;
48926
+ return `${gapText} \u2014 ${formatTemporalTimestamp(new Date(timestamp))}`;
48651
48927
  }
48652
48928
  function getTemporalGapReminderMetadata(message, gapText, gapMs, timestamp) {
48653
48929
  const formattedTimestamp = formatTemporalTimestamp(new Date(timestamp));
@@ -48868,14 +49144,14 @@ var ObservationalMemoryProcessor = class {
48868
49144
  omDebug(`[OM:processInputStep:ENTER] step=${stepNumber}, hasMastraMemory=${!!requestContext?.get("MastraMemory")}, hasMemoryInfo=${!!messageList?.serialize()?.memoryInfo?.threadId}`);
48869
49145
  const context = this.engine.getThreadContext(requestContext, messageList);
48870
49146
  if (!context) {
48871
- omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null — returning early`);
49147
+ omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null \u2014 returning early`);
48872
49148
  return messageList;
48873
49149
  }
48874
49150
  const gatewayMemoryManaged = await isGatewayMemoryManaged(model);
48875
49151
  state[GATEWAY_STATE_KEY] = gatewayMemoryManaged;
48876
49152
  if (gatewayMemoryManaged) {
48877
49153
  await this.endActiveTurn(state);
48878
- omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory — skipping local processing`);
49154
+ omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory \u2014 skipping local processing`);
48879
49155
  return messageList;
48880
49156
  }
48881
49157
  const { threadId, resourceId } = context;
@@ -49096,7 +49372,7 @@ var ObservationalMemoryProcessor = class {
49096
49372
  if (!context) return;
49097
49373
  if ((0, _mastra_core_memory.parseMemoryRequestContext)(requestContext)?.memoryConfig?.readOnly) return;
49098
49374
  state[CONTEXT_OVERFLOW_STEP_KEY] = stepNumber;
49099
- omDebug(`[OM:processAPIError] context overflow at step ${stepNumber} — observing pending messages`);
49375
+ omDebug(`[OM:processAPIError] context overflow at step ${stepNumber} \u2014 observing pending messages`);
49100
49376
  const { threadId, resourceId } = context;
49101
49377
  await this.engine.waitForBuffering(threadId, resourceId, void 0, args.abortSignal);
49102
49378
  const messages = getObservableMessages(messageList);
@@ -51695,7 +51971,7 @@ var require_ignore = /* @__PURE__ */ require_rolldown_runtime.__commonJSMin(((ex
51695
51971
  const SPACE = " ";
51696
51972
  const ESCAPE = "\\";
51697
51973
  const REGEX_LITERAL_SPECIAL = /[.*+?()[\]{}^$|\\/]/;
51698
- const BOM = "";
51974
+ const BOM = "\uFEFF";
51699
51975
  const REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
51700
51976
  const REGEX_ANCHORED_GLOBSTAR = /^\/\*{2,}$/;
51701
51977
  const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
@@ -51792,8 +52068,8 @@ var require_ignore = /* @__PURE__ */ require_rolldown_runtime.__commonJSMin(((ex
51792
52068
  const NEVER_MATCH = "[]";
51793
52069
  const PLACEHOLDER = "\0";
51794
52070
  const REGEX_RESTORE_PLACEHOLDER = new RegExp(`${PLACEHOLDER}(\\d+)${PLACEHOLDER}`, "g");
51795
- const TRAILING_WILDCARD = "";
51796
- const TRAILING_DOUBLESTAR = "";
52071
+ const TRAILING_WILDCARD = "\uE000";
52072
+ const TRAILING_DOUBLESTAR = "\uE001";
51797
52073
  const isReserved = (char) => char === PLACEHOLDER || char === TRAILING_WILDCARD || char === TRAILING_DOUBLESTAR;
51798
52074
  const extractBrackets = (pattern) => {
51799
52075
  const sources = [];
@@ -52565,7 +52841,7 @@ async function logGitState(targetPath, label) {
52565
52841
  const gitStatusResult = await git(targetPath, "status", "--porcelain");
52566
52842
  const gitLogResult = await git(targetPath, "log", "--oneline", "-3");
52567
52843
  const gitCountResult = await git(targetPath, "rev-list", "--count", "HEAD");
52568
- console.info(`📊 Git state ${label}:`);
52844
+ console.info(`\u{1F4CA} Git state ${label}:`);
52569
52845
  console.info("Status:", gitStatusResult.stdout.trim() || "Clean working directory");
52570
52846
  console.info("Recent commits:", gitLogResult.stdout.trim());
52571
52847
  console.info("Total commits:", gitCountResult.stdout.trim());
@@ -52657,9 +52933,9 @@ async function gitCheckoutBranch(branchName, targetPath) {
52657
52933
  async function backupAndReplaceFile(sourceFile, targetFile) {
52658
52934
  const backupFile = `${targetFile}.backup-${Date.now()}`;
52659
52935
  await (0, fs_promises.copyFile)(targetFile, backupFile);
52660
- console.info(`📦 Created backup: ${(0, path.basename)(backupFile)}`);
52936
+ console.info(`\u{1F4E6} Created backup: ${(0, path.basename)(backupFile)}`);
52661
52937
  await (0, fs_promises.copyFile)(sourceFile, targetFile);
52662
- console.info(`🔄 Replaced file with template version (backup created)`);
52938
+ console.info(`\u{1F504} Replaced file with template version (backup created)`);
52663
52939
  }
52664
52940
  async function renameAndCopyFile(sourceFile, targetFile) {
52665
52941
  let counter = 1;
@@ -52673,7 +52949,7 @@ async function renameAndCopyFile(sourceFile, targetFile) {
52673
52949
  counter++;
52674
52950
  }
52675
52951
  await (0, fs_promises.copyFile)(sourceFile, uniqueTargetFile);
52676
- console.info(`📝 Copied with unique name: ${(0, path.basename)(uniqueTargetFile)}`);
52952
+ console.info(`\u{1F4DD} Copied with unique name: ${(0, path.basename)(uniqueTargetFile)}`);
52677
52953
  return uniqueTargetFile;
52678
52954
  }
52679
52955
  const isValidMastraLanguageModel = (model) => {
@@ -52711,7 +52987,7 @@ const mergeGitignoreFiles = (targetContent, templateContent, templateSlug) => {
52711
52987
  const isNegation = normalized.startsWith("!");
52712
52988
  const basePath = isNegation ? normalized.slice(1) : normalized;
52713
52989
  if (!(isNegation ? existingEntries.has(basePath) : existingEntries.has("!" + basePath))) newEntries.push(trimmed);
52714
- else console.info(`⚠ Skipping conflicting .gitignore rule: ${trimmed} (conflicts with existing rule)`);
52990
+ else console.info(`\u26A0 Skipping conflicting .gitignore rule: ${trimmed} (conflicts with existing rule)`);
52715
52991
  }
52716
52992
  }
52717
52993
  }
@@ -52741,7 +53017,7 @@ const mergeEnvFiles = (targetContent, templateVariables, templateSlug) => {
52741
53017
  key,
52742
53018
  value
52743
53019
  });
52744
- else console.info(`⚠ Skipping existing environment variable: ${key} (already exists in .env)`);
53020
+ else console.info(`\u26A0 Skipping existing environment variable: ${key} (already exists in .env)`);
52745
53021
  if (newVars.length === 0) return targetContent;
52746
53022
  const result = [...targetLines];
52747
53023
  const lastLine = result[result.length - 1];
@@ -52796,7 +53072,7 @@ const createModelInstance = async (provider, modelId, version = "v2") => {
52796
53072
  try {
52797
53073
  const providerFn = version === `v1` ? { v1: {
52798
53074
  openai: async () => {
52799
- const { openai } = await Promise.resolve().then(() => require("./dist-C0Das1QD.cjs"));
53075
+ const { openai } = await Promise.resolve().then(() => require("./dist-uiPbWl5E.cjs"));
52800
53076
  return openai(modelId);
52801
53077
  },
52802
53078
  anthropic: async () => {
@@ -52865,25 +53141,25 @@ IF NO PROJECT EXISTS, USE THE MANAGEPROJECT TOOL TO CREATE A NEW PROJECT
52865
53141
 
52866
53142
  DO NOT INCLUDE TODOS IN THE CODE, UNLESS SPECIFICALLY ASKED TO DO SO, CREATE REAL WORLD CODE
52867
53143
 
52868
- ### 1. 🔍 **UNDERSTAND** (Information Gathering)
53144
+ ### 1. \u{1F50D} **UNDERSTAND** (Information Gathering)
52869
53145
  - **Explore Mastra Docs**: Use docs tools to understand relevant Mastra patterns and APIs
52870
53146
  - **Analyze Project**: Use file exploration to understand existing codebase structure
52871
53147
  - **Web Research**: Search for packages, examples, or solutions when docs are insufficient
52872
53148
  - **Clarify Requirements**: Ask targeted questions only when critical information is missing
52873
53149
 
52874
- ### 2. 📋 **PLAN** (Strategy & Design)
53150
+ ### 2. \u{1F4CB} **PLAN** (Strategy & Design)
52875
53151
  - **Architecture**: Design using Mastra conventions (agents, tools, workflows, memory)
52876
53152
  - **Dependencies**: Identify required packages and Mastra components
52877
53153
  - **Integration**: Plan how to integrate with existing project structure
52878
53154
  - **Validation**: Define how to test and verify the implementation
52879
53155
 
52880
- ### 3. 🛠️ **BUILD** (Implementation)
53156
+ ### 3. \u{1F6E0}\uFE0F **BUILD** (Implementation)
52881
53157
  - **Install First**: Use \`manageProject\` tool to install required packages
52882
53158
  - **Follow Patterns**: Implement using established Mastra conventions
52883
53159
  - **Real Code Only**: Build actual working functionality, never mock implementations
52884
53160
  - **Environment Setup**: Create proper .env configuration and documentation
52885
53161
 
52886
- ### 4. ✅ **VALIDATE** (Quality Assurance)
53162
+ ### 4. \u2705 **VALIDATE** (Quality Assurance)
52887
53163
  - **Code Validation**: Run \`validateCode\` with types and lint checks
52888
53164
  - **Testing**: Execute tests if available
52889
53165
  - **Server Testing**: Use \`manageServer\` and \`httpRequest\` for API validation
@@ -52980,23 +53256,23 @@ DO NOT INCLUDE TODOS IN THE CODE, UNLESS SPECIFICALLY ASKED TO DO SO, CREATE REA
52980
53256
  ## Output Requirements
52981
53257
 
52982
53258
  ### Code Quality
52983
- - ✅ TypeScript compilation passes
52984
- - ✅ ESLint validation passes
52985
- - ✅ Proper error handling implemented
52986
- - ✅ Environment variables configured
52987
- - ✅ Tests included when appropriate
53259
+ - \u2705 TypeScript compilation passes
53260
+ - \u2705 ESLint validation passes
53261
+ - \u2705 Proper error handling implemented
53262
+ - \u2705 Environment variables configured
53263
+ - \u2705 Tests included when appropriate
52988
53264
 
52989
53265
  ### Documentation
52990
- - ✅ Clear setup instructions
52991
- - ✅ Environment variable documentation
52992
- - ✅ Usage examples provided
52993
- - ✅ API documentation for custom tools
53266
+ - \u2705 Clear setup instructions
53267
+ - \u2705 Environment variable documentation
53268
+ - \u2705 Usage examples provided
53269
+ - \u2705 API documentation for custom tools
52994
53270
 
52995
53271
  ### Integration
52996
- - ✅ Follows Mastra conventions
52997
- - ✅ Integrates with existing project
52998
- - ✅ Proper imports and exports
52999
- - ✅ Compatible with Mastra ecosystem
53272
+ - \u2705 Follows Mastra conventions
53273
+ - \u2705 Integrates with existing project
53274
+ - \u2705 Proper imports and exports
53275
+ - \u2705 Compatible with Mastra ecosystem
53000
53276
 
53001
53277
  ## Project Context
53002
53278
 
@@ -53543,7 +53819,7 @@ export const mastra = new Mastra({
53543
53819
  }),
53544
53820
  validateCode: (0, _mastra_core_tools.createTool)({
53545
53821
  id: "validate-code",
53546
- description: "Validates code using a fast hybrid approach: syntax → semantic → lint. RECOMMENDED: Always provide specific files for optimal performance and accuracy.",
53822
+ description: "Validates code using a fast hybrid approach: syntax \u2192 semantic \u2192 lint. RECOMMENDED: Always provide specific files for optimal performance and accuracy.",
53547
53823
  inputSchema: zod.z.object({
53548
53824
  projectPath: zod.z.string().optional().describe("Path to the project to validate (defaults to current project)"),
53549
53825
  validationType: zod.z.array(zod.z.enum([
@@ -53553,7 +53829,7 @@ export const mastra = new Mastra({
53553
53829
  "tests",
53554
53830
  "build"
53555
53831
  ])).describe("Types of validation to perform. Recommended: [\"types\", \"lint\"] for code quality"),
53556
- files: zod.z.array(zod.z.string()).optional().describe("RECOMMENDED: Specific files to validate (e.g., files you created/modified). Uses hybrid validation: fast syntax check → semantic types → ESLint. Without files, falls back to slower CLI validation.")
53832
+ files: zod.z.array(zod.z.string()).optional().describe("RECOMMENDED: Specific files to validate (e.g., files you created/modified). Uses hybrid validation: fast syntax check \u2192 semantic types \u2192 ESLint. Without files, falls back to slower CLI validation.")
53557
53833
  }),
53558
53834
  outputSchema: zod.z.object({
53559
53835
  valid: zod.z.boolean(),
@@ -55436,8 +55712,8 @@ For each Mastra project directory you analyze:
55436
55712
  IMPORTANT - Naming Consistency Rules:
55437
55713
  - For ALL unit types (including 'other'), the 'name' field should be the filename WITHOUT extension
55438
55714
  - For structured units (agents, workflows, tools, etc.), prefer the actual export name if clearly identifiable
55439
- - use the base filename without extension for the id (e.g., 'util.ts' → name: 'util')
55440
- - use the relative path from the template root for the file (e.g., 'src/mastra/lib/util.ts' → file: 'src/mastra/lib/util.ts')
55715
+ - use the base filename without extension for the id (e.g., 'util.ts' \u2192 name: 'util')
55716
+ - use the relative path from the template root for the file (e.g., 'src/mastra/lib/util.ts' \u2192 file: 'src/mastra/lib/util.ts')
55441
55717
 
55442
55718
  Return the actual exported names of the units, as well as the file names.`,
55443
55719
  name: "Mastra Project Discoverer",
@@ -55793,7 +56069,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
55793
56069
  sourceFile: unit.file,
55794
56070
  targetFile: `${targetDir}/${convertedFileName}`
55795
56071
  });
55796
- console.info(`⏭️ Skipped ${unit.kind} "${unit.id}": file already exists`);
56072
+ console.info(`\u23ED\uFE0F Skipped ${unit.kind} "${unit.id}": file already exists`);
55797
56073
  continue;
55798
56074
  case "backup-and-replace": try {
55799
56075
  await backupAndReplaceFile(sourceFile, targetFile);
@@ -55805,7 +56081,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
55805
56081
  id: unit.id
55806
56082
  }
55807
56083
  });
55808
- console.info(`🔄 Replaced ${unit.kind} "${unit.id}": ${unit.file} → ${convertedFileName} (backup created)`);
56084
+ console.info(`\u{1F504} Replaced ${unit.kind} "${unit.id}": ${unit.file} \u2192 ${convertedFileName} (backup created)`);
55809
56085
  continue;
55810
56086
  } catch (backupError) {
55811
56087
  conflicts.push({
@@ -55829,7 +56105,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
55829
56105
  id: unit.id
55830
56106
  }
55831
56107
  });
55832
- console.info(`📝 Renamed ${unit.kind} "${unit.id}": ${unit.file} → ${(0, path.basename)(uniqueTargetFile)}`);
56108
+ console.info(`\u{1F4DD} Renamed ${unit.kind} "${unit.id}": ${unit.file} \u2192 ${(0, path.basename)(uniqueTargetFile)}`);
55833
56109
  continue;
55834
56110
  } catch (renameError) {
55835
56111
  conflicts.push({
@@ -55867,7 +56143,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
55867
56143
  id: unit.id
55868
56144
  }
55869
56145
  });
55870
- console.info(`✓ Copied ${unit.kind} "${unit.id}": ${unit.file} → ${convertedFileName}`);
56146
+ console.info(`\u2713 Copied ${unit.kind} "${unit.id}": ${unit.file} \u2192 ${convertedFileName}`);
55871
56147
  } catch (copyError) {
55872
56148
  conflicts.push({
55873
56149
  unit: {
@@ -55894,7 +56170,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
55894
56170
  id: "tsconfig.json"
55895
56171
  }
55896
56172
  });
55897
- console.info("✓ Copied tsconfig.json from template to target");
56173
+ console.info("\u2713 Copied tsconfig.json from template to target");
55898
56174
  } else {
55899
56175
  await (0, fs_promises.writeFile)(targetTsconfig, JSON.stringify({
55900
56176
  compilerOptions: {
@@ -55930,7 +56206,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
55930
56206
  id: "tsconfig.json"
55931
56207
  }
55932
56208
  });
55933
- console.info("✓ Generated minimal tsconfig.json in target");
56209
+ console.info("\u2713 Generated minimal tsconfig.json in target");
55934
56210
  }
55935
56211
  }
55936
56212
  } catch (e) {
@@ -55959,7 +56235,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
55959
56235
  id: "mastra-index"
55960
56236
  }
55961
56237
  });
55962
- console.info("✓ Copied Mastra index file from template");
56238
+ console.info("\u2713 Copied Mastra index file from template");
55963
56239
  }
55964
56240
  }
55965
56241
  } catch (e) {
@@ -55988,7 +56264,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
55988
56264
  id: "gitignore"
55989
56265
  }
55990
56266
  });
55991
- console.info("✓ Copied .gitignore from template to target");
56267
+ console.info("\u2713 Copied .gitignore from template to target");
55992
56268
  } else {
55993
56269
  const targetContent = await (0, fs_promises.readFile)(targetGitignore, "utf-8");
55994
56270
  const templateContent = await (0, fs_promises.readFile)(templateGitignore, "utf-8");
@@ -56004,8 +56280,8 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
56004
56280
  id: "gitignore-merge"
56005
56281
  }
56006
56282
  });
56007
- console.info(`✓ Merged template .gitignore entries into existing .gitignore (${addedLines} new entries)`);
56008
- } else console.info("ℹ No new .gitignore entries to add from template");
56283
+ console.info(`\u2713 Merged template .gitignore entries into existing .gitignore (${addedLines} new entries)`);
56284
+ } else console.info("\u2139 No new .gitignore entries to add from template");
56009
56285
  }
56010
56286
  }
56011
56287
  } catch (e) {
@@ -56034,7 +56310,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
56034
56310
  id: "env"
56035
56311
  }
56036
56312
  });
56037
- console.info(`✓ Created .env file with ${Object.keys(variables).length} template variables`);
56313
+ console.info(`\u2713 Created .env file with ${Object.keys(variables).length} template variables`);
56038
56314
  } else {
56039
56315
  const targetContent = await (0, fs_promises.readFile)(targetEnv, "utf-8");
56040
56316
  const mergedContent = mergeEnvFiles(targetContent, variables, slug);
@@ -56049,8 +56325,8 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
56049
56325
  id: "env-merge"
56050
56326
  }
56051
56327
  });
56052
- console.info(`✓ Merged new environment variables into existing .env file (${addedLines} new entries)`);
56053
- } else console.info("ℹ No new environment variables to add (all already exist in .env)");
56328
+ console.info(`\u2713 Merged new environment variables into existing .env file (${addedLines} new entries)`);
56329
+ } else console.info("\u2139 No new environment variables to add (all already exist in .env)");
56054
56330
  }
56055
56331
  }
56056
56332
  } catch (e) {
@@ -56067,7 +56343,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
56067
56343
  if (copiedFiles.length > 0) try {
56068
56344
  const fileList = copiedFiles.map((f) => f.destination);
56069
56345
  await gitAddAndCommit(targetPath, `feat(template): copy ${copiedFiles.length} files from ${slug}@${commitSha.substring(0, 7)}`, fileList, { skipIfNoStaged: true });
56070
- console.info(`✓ Committed ${copiedFiles.length} copied files`);
56346
+ console.info(`\u2713 Committed ${copiedFiles.length} copied files`);
56071
56347
  } catch (commitError) {
56072
56348
  console.warn("Failed to commit copied files:", commitError);
56073
56349
  }
@@ -56311,7 +56587,7 @@ Start by listing your tasks and work through them systematically!
56311
56587
  content: toolResult.content || "",
56312
56588
  notes: toolResult.notes
56313
56589
  });
56314
- console.info(`📋 Task completed: ${toolResult.taskId} - ${toolResult.content}`);
56590
+ console.info(`\u{1F4CB} Task completed: ${toolResult.taskId} - ${toolResult.content}`);
56315
56591
  }
56316
56592
  } catch (parseError) {
56317
56593
  console.warn("Failed to parse task management result:", parseError);
@@ -56363,7 +56639,7 @@ const validationAndFixStep = (0, _mastra_core_workflows.createStep)({
56363
56639
  const { commitSha, slug, orderedUnits, templateDir, copiedFiles, conflictsResolved, maxIterations = 5 } = inputData;
56364
56640
  const targetPath = resolveTargetPath(inputData, requestContext);
56365
56641
  if (!(copiedFiles.length > 0 || conflictsResolved && conflictsResolved.length > 0)) {
56366
- console.info("⏭️ Skipping validation - no files copied or conflicts resolved");
56642
+ console.info("\u23ED\uFE0F Skipping validation - no files copied or conflicts resolved");
56367
56643
  return {
56368
56644
  success: true,
56369
56645
  applied: false,
@@ -56375,7 +56651,7 @@ const validationAndFixStep = (0, _mastra_core_workflows.createStep)({
56375
56651
  }
56376
56652
  };
56377
56653
  }
56378
- console.info(`📋 Changes detected: ${copiedFiles.length} files copied, ${conflictsResolved?.length || 0} conflicts resolved`);
56654
+ console.info(`\u{1F4CB} Changes detected: ${copiedFiles.length} files copied, ${conflictsResolved?.length || 0} conflicts resolved`);
56379
56655
  let currentIteration = 1;
56380
56656
  try {
56381
56657
  const model = await resolveModel({
@@ -56467,7 +56743,7 @@ CRITICAL TOOL SELECTION GUIDE:
56467
56743
  - **writeFile**: ONLY for creating new files that don't exist
56468
56744
  Example: creating missing index.ts barrel files
56469
56745
 
56470
- CRITICAL WRITEFILЕ SAFETY RULES:
56746
+ CRITICAL WRITEFIL\u0415 SAFETY RULES:
56471
56747
  - ONLY use writeFile for creating NEW files that don't exist
56472
56748
  - ALWAYS check with readFile first to verify file doesn't exist
56473
56749
  - NEVER use writeFile to overwrite existing files - use multiEdit or replaceLines instead
@@ -56552,10 +56828,10 @@ Previous iterations may have fixed some issues, so start by re-running validateC
56552
56828
  if (iterationErrors > 0 && lastValidationResult?.errors) validationResults.lastValidationErrors = lastValidationResult.errors;
56553
56829
  console.info(`Iteration ${currentIteration} complete: ${iterationErrors} errors remaining`);
56554
56830
  if (iterationErrors === 0) {
56555
- console.info(`✅ All validation issues resolved in ${currentIteration} iterations!`);
56831
+ console.info(`\u2705 All validation issues resolved in ${currentIteration} iterations!`);
56556
56832
  break;
56557
56833
  } else if (currentIteration >= maxIterations) {
56558
- console.info(`⚠️ Max iterations (${maxIterations}) reached. ${iterationErrors} errors still remaining.`);
56834
+ console.info(`\u26A0\uFE0F Max iterations (${maxIterations}) reached. ${iterationErrors} errors still remaining.`);
56559
56835
  break;
56560
56836
  }
56561
56837
  currentIteration++;
@@ -56595,7 +56871,7 @@ Previous iterations may have fixed some issues, so start by re-running validateC
56595
56871
  recursive: true,
56596
56872
  force: true
56597
56873
  });
56598
- console.info(`✓ Cleaned up template directory: ${templateDir}`);
56874
+ console.info(`\u2713 Cleaned up template directory: ${templateDir}`);
56599
56875
  } catch (cleanupError) {
56600
56876
  console.warn("Failed to cleanup template directory:", cleanupError);
56601
56877
  }
@@ -59689,11 +59965,11 @@ function createPlanningAndApprovalWorkflow() {
59689
59965
  }
59690
59966
  createPlanningAndApprovalWorkflow();
59691
59967
  const workflowResearch = `
59692
- ## 🔍 **COMPREHENSIVE MASTRA WORKFLOW RESEARCH SUMMARY**
59968
+ ## \u{1F50D} **COMPREHENSIVE MASTRA WORKFLOW RESEARCH SUMMARY**
59693
59969
 
59694
59970
  Based on extensive research of Mastra documentation and examples, here's essential information for building effective Mastra workflows:
59695
59971
 
59696
- ### **📋 WORKFLOW FUNDAMENTALS**
59972
+ ### **\u{1F4CB} WORKFLOW FUNDAMENTALS**
59697
59973
 
59698
59974
  **Core Components:**
59699
59975
  - **\`createWorkflow()\`**: Main factory function that creates workflow instances
@@ -59717,7 +59993,7 @@ const workflow = createWorkflow({
59717
59993
  .commit(); // CRITICAL: Makes workflow executable
59718
59994
  \`\`\`
59719
59995
 
59720
- ### **🔧 STEP CREATION PATTERNS**
59996
+ ### **\u{1F527} STEP CREATION PATTERNS**
59721
59997
 
59722
59998
  **Standard Step Definition:**
59723
59999
  \`\`\`typescript
@@ -59741,7 +60017,7 @@ const myStep = createStep({
59741
60017
  - \`requestContext\`: Runtime dependency injection context
59742
60018
  - \`runCount\`: Number of times this step has run (useful for retries)
59743
60019
 
59744
- ### **🔄 CONTROL FLOW METHODS**
60020
+ ### **\u{1F504} CONTROL FLOW METHODS**
59745
60021
 
59746
60022
  **Sequential Execution:**
59747
60023
  - \`.then(step)\`: Execute steps one after another
@@ -59763,7 +60039,7 @@ const myStep = createStep({
59763
60039
  **Data Transformation:**
59764
60040
  - \`.map(({ inputData, getStepResult, getInitData }) => transformedData)\`: Transform data between steps
59765
60041
 
59766
- ### **⏸️ SUSPEND & RESUME CAPABILITIES**
60042
+ ### **\u23F8\uFE0F SUSPEND & RESUME CAPABILITIES**
59767
60043
 
59768
60044
  **For Human-in-the-Loop Workflows:**
59769
60045
  \`\`\`typescript
@@ -59794,7 +60070,7 @@ if (result.status === "suspended") {
59794
60070
  }
59795
60071
  \`\`\`
59796
60072
 
59797
- ### **🛠️ INTEGRATING AGENTS & TOOLS**
60073
+ ### **\u{1F6E0}\uFE0F INTEGRATING AGENTS & TOOLS**
59798
60074
 
59799
60075
  **Using Agents in Steps:**
59800
60076
  \`\`\`typescript
@@ -59827,24 +60103,24 @@ const step = createStep({
59827
60103
  });
59828
60104
  \`\`\`
59829
60105
 
59830
- ### **🗂️ PROJECT ORGANIZATION PATTERNS**
60106
+ ### **\u{1F5C2}\uFE0F PROJECT ORGANIZATION PATTERNS**
59831
60107
 
59832
60108
  **MANDATORY Workflow Organization:**
59833
60109
  Each workflow MUST be organized in its own dedicated folder with separated concerns:
59834
60110
 
59835
60111
  \`\`\`
59836
60112
  src/mastra/workflows/
59837
- ├── my-workflow-name/ # Kebab-case folder name
59838
- │ ├── types.ts # All Zod schemas and TypeScript types
59839
- │ ├── steps.ts # All individual step definitions
59840
- │ ├── workflow.ts # Main workflow composition and export
59841
- │ └── utils.ts # Helper functions (if needed)
59842
- ├── another-workflow/
59843
- │ ├── types.ts
59844
- │ ├── steps.ts
59845
- │ ├── workflow.ts
59846
- │ └── utils.ts
59847
- └── index.ts # Export all workflows
60113
+ \u251C\u2500\u2500 my-workflow-name/ # Kebab-case folder name
60114
+ \u2502 \u251C\u2500\u2500 types.ts # All Zod schemas and TypeScript types
60115
+ \u2502 \u251C\u2500\u2500 steps.ts # All individual step definitions
60116
+ \u2502 \u251C\u2500\u2500 workflow.ts # Main workflow composition and export
60117
+ \u2502 \u2514\u2500\u2500 utils.ts # Helper functions (if needed)
60118
+ \u251C\u2500\u2500 another-workflow/
60119
+ \u2502 \u251C\u2500\u2500 types.ts
60120
+ \u2502 \u251C\u2500\u2500 steps.ts
60121
+ \u2502 \u251C\u2500\u2500 workflow.ts
60122
+ \u2502 \u2514\u2500\u2500 utils.ts
60123
+ \u2514\u2500\u2500 index.ts # Export all workflows
59848
60124
  \`\`\`
59849
60125
 
59850
60126
  **CRITICAL File Organization Rules:**
@@ -59868,7 +60144,7 @@ export const mastra = new Mastra({
59868
60144
  });
59869
60145
  \`\`\`
59870
60146
 
59871
- ### **📦 ESSENTIAL DEPENDENCIES**
60147
+ ### **\u{1F4E6} ESSENTIAL DEPENDENCIES**
59872
60148
 
59873
60149
  **Required Packages:**
59874
60150
  \`\`\`json
@@ -59885,7 +60161,7 @@ export const mastra = new Mastra({
59885
60161
  - \`@ai-sdk/openai\`: For AI model integration
59886
60162
  - \`ai\`: For AI SDK functionality
59887
60163
 
59888
- ### **✅ WORKFLOW BEST PRACTICES**
60164
+ ### **\u2705 WORKFLOW BEST PRACTICES**
59889
60165
 
59890
60166
  **Schema Design:**
59891
60167
  - Use descriptive property names in schemas
@@ -59907,7 +60183,7 @@ export const mastra = new Mastra({
59907
60183
  - Access previous step results with \`getStepResult(stepInstance)\`
59908
60184
  - Use \`getInitData()\` to access original workflow input
59909
60185
 
59910
- ### **🚀 EXECUTION PATTERNS**
60186
+ ### **\u{1F680} EXECUTION PATTERNS**
59911
60187
 
59912
60188
  **Running Workflows:**
59913
60189
  \`\`\`typescript
@@ -59930,7 +60206,7 @@ run.watch((event) => console.log(event));
59930
60206
  - \`"suspended"\`: Paused awaiting input
59931
60207
  - \`"failed"\`: Encountered error
59932
60208
 
59933
- ### **🔗 ADVANCED FEATURES**
60209
+ ### **\u{1F517} ADVANCED FEATURES**
59934
60210
 
59935
60211
  **Nested Workflows:**
59936
60212
  - Use workflows as steps: \`.then(otherWorkflow)\`
@@ -59993,11 +60269,11 @@ CRITICAL WORKFLOW EXECUTION REQUIREMENTS:
59993
60269
  MANDATORY WORKFLOW FOLDER STRUCTURE:
59994
60270
  When ${context.action === "create" ? "creating a new workflow" : "editing a workflow"}, you MUST organize files as follows:
59995
60271
 
59996
- 📁 src/mastra/workflows/${context.workflowName?.toLowerCase().replace(/[^a-z0-9]/g, "-") || "new-workflow"}/
59997
- ├── 📄 types.ts # All Zod schemas and TypeScript types
59998
- ├── 📄 steps.ts # All individual step definitions
59999
- ├── 📄 workflow.ts # Main workflow composition and export
60000
- └── 📄 utils.ts # Helper functions (if needed)
60272
+ \u{1F4C1} src/mastra/workflows/${context.workflowName?.toLowerCase().replace(/[^a-z0-9]/g, "-") || "new-workflow"}/
60273
+ \u251C\u2500\u2500 \u{1F4C4} types.ts # All Zod schemas and TypeScript types
60274
+ \u251C\u2500\u2500 \u{1F4C4} steps.ts # All individual step definitions
60275
+ \u251C\u2500\u2500 \u{1F4C4} workflow.ts # Main workflow composition and export
60276
+ \u2514\u2500\u2500 \u{1F4C4} utils.ts # Helper functions (if needed)
60001
60277
 
60002
60278
  CRITICAL FILE ORGANIZATION RULES:
60003
60279
  - **ALWAYS create a dedicated folder** for the workflow in src/mastra/workflows/
@@ -60069,7 +60345,7 @@ ${context.resumeData ? `USER PROVIDED ANSWERS: ${JSON.stringify(context.resumeDa
60069
60345
  },
60070
60346
  validation: { instructions: `CRITICAL VALIDATION INSTRUCTIONS:
60071
60347
  - When using the validateCode tool, ALWAYS pass the specific files you created or modified using the 'files' parameter
60072
- - The tool uses a hybrid validation approach: fast syntax checking → semantic type checking → ESLint
60348
+ - The tool uses a hybrid validation approach: fast syntax checking \u2192 semantic type checking \u2192 ESLint
60073
60349
  - This is much faster than full project compilation and only shows errors from your specific files
60074
60350
  - Example: validateCode({ validationType: ['types', 'lint'], files: ['src/workflows/my-workflow.ts', 'src/agents/my-agent.ts'] })
60075
60351
  - ALWAYS validate after creating or modifying files to ensure they compile correctly` }