@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
@@ -8,12 +8,12 @@ import { any, array, boolean, custom, discriminatedUnion, enum as enum$1, instan
8
8
  import { isStandardSchemaWithJSON, toStandardSchema } from "@mastra/core/schema";
9
9
  import { ZodFirstPartyTypeKind } from "zod/v3";
10
10
  import { z as z$2 } from "zod";
11
+ import { inspect, promisify } from "util";
11
12
  import { MESSAGE_EMBEDDING_CHARS_PER_TOKEN, MastraMemory, buildMessageEmbeddingRows, chunkMessageText, getMemoryTokenBoundary, getThreadOMMetadata, isAfterMemoryTokenBoundary, isThreadTitlePinned, loadMessageHistory, normalizeMessageHistoryConfig, parseMemoryRequestContext, resolveMaxChunkChars, setThreadOMMetadata, upsertMessageVectors } from "@mastra/core/memory";
12
13
  import { Agent, MessageList, isSupportedLanguageModel, tryGenerateWithJsonFallback, tryStreamWithJsonFallback } from "@mastra/core/agent";
13
14
  import { ErrorCategory, ErrorDomain, MastraError, classifyProviderError } from "@mastra/core/error";
14
15
  import { ModelRouterLanguageModel, modelSupportsAttachments, modelSupportsTemperature, resolveModelConfig } from "@mastra/core/llm";
15
16
  import { createTool } from "@mastra/core/tools";
16
- import { inspect, promisify } from "util";
17
17
  import { MASTRA_THREAD_ID_KEY, RequestContext } from "@mastra/core/request-context";
18
18
  import { generateEmptyFromSchema } from "@mastra/core/utils";
19
19
  import { InMemoryStore } from "@mastra/core/storage";
@@ -896,7 +896,7 @@ var require_jpeg = /* @__PURE__ */ __commonJSMin$1(((exports) => {
896
896
  var str2arr = require_utils().str2arr;
897
897
  var sliceEq = require_utils().sliceEq;
898
898
  var exifOrientation = require_exif_orientation_parser();
899
- var SIG_JPEG = str2arr("ÿØÿ");
899
+ var SIG_JPEG = str2arr("\u00FF\u00D8\u00FF");
900
900
  var SIG_EXIF = str2arr("Exif\0\0");
901
901
  var S_SIGNATURE = 0;
902
902
  var S_MARKER_START = 1;
@@ -1042,7 +1042,7 @@ var require_png = /* @__PURE__ */ __commonJSMin$1(((exports) => {
1042
1042
  var str2arr = require_utils().str2arr;
1043
1043
  var sliceEq = require_utils().sliceEq;
1044
1044
  var readUInt32BE = require_read_le_be().readUInt32BE;
1045
- var SIG_PNG = str2arr("‰PNG\r\n\n");
1045
+ var SIG_PNG = str2arr("\u0089PNG\r\n\n");
1046
1046
  var SIG_IHDR = str2arr("IHDR");
1047
1047
  function PngParser() {
1048
1048
  this.partial_buffer = /* @__PURE__ */ new Uint8Array(24);
@@ -8655,7 +8655,7 @@ function splitLines(text) {
8655
8655
  else result.push(result.pop().slice(0, -1));
8656
8656
  return result;
8657
8657
  }
8658
- // ../memory/dist/src-CRmfe-8x.js
8658
+ // ../memory/dist/src-TRQ73bGO.js
8659
8659
  var __defProp$3 = Object.defineProperty;
8660
8660
  var __exportAll = (all, no_symbols) => {
8661
8661
  let target = {};
@@ -32876,14 +32876,14 @@ function getRetrievalInstructions(scope = "resource", customInstructions, search
32876
32876
  The recall tool works across ALL of this user's conversation threads, not just the current one.
32877
32877
 
32878
32878
  - 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.
32879
- - 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.
32879
+ - 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.
32880
32880
  - 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.
32881
32881
 
32882
- **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
32882
+ **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
32883
32883
  The recall tool works across ALL of this user's conversation threads, not just the current one.
32884
32884
 
32885
32885
  - 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.
32886
- - Use \`mode: "messages"\` when you know the thread — pass \`threadId\` to read another thread, or a \`cursor\` from an observation-group range.
32886
+ - Use \`mode: "messages"\` when you know the thread \u2014 pass \`threadId\` to read another thread, or a \`cursor\` from an observation-group range.
32887
32887
 
32888
32888
  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
32889
32889
  The recall tool is limited to the current conversation thread.
@@ -32908,7 +32908,7 @@ When searches keep returning the same groups, often as already-in-context refere
32908
32908
  "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.
32909
32909
 
32910
32910
  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.` : "";
32911
- const base = `## Recall — looking up source messages
32911
+ const base = `## Recall \u2014 looking up source messages
32912
32912
 
32913
32913
  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.
32914
32914
 
@@ -32919,13 +32919,13 @@ Groups marked \`kind="reflection"\` (rendered as \`_kind: reflection_\`) are los
32919
32919
 
32920
32920
  ### When to use recall
32921
32921
  - The user asks you to **repeat, show, or reproduce** something from a past conversation
32922
- - The user asks for **exact content** — code, text, quotes, error messages, URLs, file paths, specific numbers
32922
+ - The user asks for **exact content** \u2014 code, text, quotes, error messages, URLs, file paths, specific numbers
32923
32923
  - 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)
32924
32924
  - You want to **verify or expand on** an observation before responding
32925
32925
  - 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
32926
32926
  - 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
32927
32927
  - Relevant details are missing, ambiguous, or conflicting in the current observations${isResource ? `
32928
- - The user references another conversation that your observations don't cover — even if you have no observations yet, their other threads may contain it` : ""}
32928
+ - 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` : ""}
32929
32929
 
32930
32930
  **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.
32931
32931
 
@@ -32960,17 +32960,17 @@ Each range has the format \`startId:endId\` where both are message IDs separated
32960
32960
  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.
32961
32961
 
32962
32962
  - 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.
32963
- - 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.
32963
+ - 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.
32964
32964
 
32965
32965
  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.
32966
32966
 
32967
32967
  ### Following up on truncated parts
32968
32968
  Low-detail results may include truncation hints like:
32969
- \`[truncated — call recall cursor="..." partIndex=N detail="high" for full content]\`
32969
+ \`[truncated \u2014 call recall cursor="..." partIndex=N detail="high" for full content]\`
32970
32970
 
32971
32971
  **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.
32972
32972
 
32973
- 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.
32973
+ 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.
32974
32974
 
32975
32975
  ### When recall is NOT needed
32976
32976
  - The user is asking for a high-level summary and your observations already cover it
@@ -33365,6 +33365,15 @@ function buildThreadMetadataFromExtractedValues(extractors, values) {
33365
33365
  async function applyExtractorHooks(opts) {
33366
33366
  const values = normalizeExtractedValues(opts.values) ?? {};
33367
33367
  const failures = [...opts.failures ?? []];
33368
+ let recentMessages;
33369
+ let recentMessagesResolved = false;
33370
+ const resolveRecentMessages = () => {
33371
+ if (!recentMessagesResolved) {
33372
+ recentMessages = typeof opts.recentMessages === "function" ? opts.recentMessages() : opts.recentMessages;
33373
+ recentMessagesResolved = true;
33374
+ }
33375
+ return recentMessages;
33376
+ };
33368
33377
  for (const extractor of opts.extractors) {
33369
33378
  const isHook = extractor.mode === "hook";
33370
33379
  const hasValue = Object.prototype.hasOwnProperty.call(values, extractor.slug);
@@ -33384,7 +33393,9 @@ async function applyExtractorHooks(opts) {
33384
33393
  previous: isHook ? void 0 : opts.previousValues?.[extractor.slug],
33385
33394
  current,
33386
33395
  rawObservations: opts.rawObservations,
33387
- recentMessages: opts.recentMessages,
33396
+ get recentMessages() {
33397
+ return resolveRecentMessages();
33398
+ },
33388
33399
  mainAgent: opts.mainAgent,
33389
33400
  memory: opts.memory,
33390
33401
  sendSignal: opts.sendSignal,
@@ -34088,7 +34099,7 @@ const YEAR = String.raw`(?:19|20|21)\d{2}(?!\d)`;
34088
34099
  const MERIDIEM = String.raw`(?:[AaPp]\.[Mm]\.|[AaPp][Mm]\b)`;
34089
34100
  const TIME = String.raw`(?:,?\s+(?:at\s+)?\d{1,2}:\d{2}(?:\s*${MERIDIEM})?|\s+at\s+\d{1,2}\s*${MERIDIEM})`;
34090
34101
  const QUALIFIER = String.raw`(?:(?:early|mid|late)[- ](?:to[- ](?:early|mid|late)[- ])?)`;
34091
- const RANGE_SEP = String.raw`(?:\s*[–—]\s*|\s*-\s*|\s+(?:to|through|until)\s+)`;
34102
+ const RANGE_SEP = String.raw`(?:\s*[\u2013\u2014]\s*|\s*-\s*|\s+(?:to|through|until)\s+)`;
34092
34103
  /**
34093
34104
  * Dates written into observation text that carry their own year, longest forms first:
34094
34105
  * "Mar 1 - Mar 18, 2025", "May 27-28, 2023", "January 10, 2024 at 3:00 PM",
@@ -34389,15 +34400,15 @@ const SHORT_TOKEN_THRESHOLD = 3;
34389
34400
  const KANA_CHARS_PER_TOKEN = 1.35;
34390
34401
  const DEFAULT_LANGUAGE_CONFIGS = [
34391
34402
  {
34392
- pattern: /[äöüßẞ]/i,
34403
+ pattern: /[\u00E4\u00F6\u00FC\u00DF\u1E9E]/i,
34393
34404
  averageCharsPerToken: 2.6
34394
34405
  },
34395
34406
  {
34396
- pattern: /[éèêëàâîïôûùüÿçœæáíóúñ]/i,
34407
+ pattern: /[\u00E9\u00E8\u00EA\u00EB\u00E0\u00E2\u00EE\u00EF\u00F4\u00FB\u00F9\u00FC\u00FF\u00E7\u0153\u00E6\u00E1\u00ED\u00F3\u00FA\u00F1]/i,
34397
34408
  averageCharsPerToken: 3
34398
34409
  },
34399
34410
  {
34400
- pattern: /[ąćęłńóśźżěščřžýůúďťň]/i,
34411
+ pattern: /[\u0105\u0107\u0119\u0142\u0144\u00F3\u015B\u017A\u017C\u011B\u0161\u010D\u0159\u017E\u00FD\u016F\u00FA\u010F\u0165\u0148]/i,
34401
34412
  averageCharsPerToken: 2.5
34402
34413
  },
34403
34414
  {
@@ -34485,10 +34496,10 @@ function sanitizeSurrogates(value) {
34485
34496
  if (next >= 56320 && next <= 57343) {
34486
34497
  sanitized += value.charAt(index) + value.charAt(index + 1);
34487
34498
  index++;
34488
- } else sanitized += "�";
34499
+ } else sanitized += "\uFFFD";
34489
34500
  continue;
34490
34501
  }
34491
- sanitized += code >= 56320 && code <= 57343 ? "�" : value[index];
34502
+ sanitized += code >= 56320 && code <= 57343 ? "\uFFFD" : value[index];
34492
34503
  }
34493
34504
  return sanitized;
34494
34505
  }
@@ -34510,7 +34521,7 @@ function truncatePath(path) {
34510
34521
  const headLength = 50;
34511
34522
  const tailLength = 60;
34512
34523
  const omitted = path.length - headLength - tailLength;
34513
- return `${safeSlice(path, headLength)}…[${omitted} chars; ${stablePathDigest(path)}]…${safeTail(path, tailLength)}`;
34524
+ return `${safeSlice(path, headLength)}\u2026[${omitted} chars; ${stablePathDigest(path)}]\u2026${safeTail(path, tailLength)}`;
34514
34525
  }
34515
34526
  function formatPath(parent, key, isArray) {
34516
34527
  if (isArray) return truncatePath(`${parent}[${key}]`);
@@ -34619,7 +34630,7 @@ function selectOutlineEntries(entries, limits) {
34619
34630
  const rendered = joinEntries(selected, marker);
34620
34631
  if (fits(rendered, limits)) return rendered;
34621
34632
  if (fits(marker, limits)) return marker;
34622
- return fits("…", limits) ? "…" : "";
34633
+ return fits("\u2026", limits) ? "\u2026" : "";
34623
34634
  }
34624
34635
  function indentPreview(value) {
34625
34636
  return value.split("\n").map((line) => ` | ${line}`).join("\n");
@@ -34662,13 +34673,13 @@ function formatToolArgumentsForObserver(value, options) {
34662
34673
  if (!isObjectLike$1(value)) {
34663
34674
  if (typeof value !== "string" || value.length <= OBSERVER_TOOL_ARGUMENT_INLINE_STRING_MAX_CHARS) {
34664
34675
  const primitive = formatPrimitive(value);
34665
- return fits(primitive, limits) ? primitive : fits("…", limits) ? "…" : "";
34676
+ return fits(primitive, limits) ? primitive : fits("\u2026", limits) ? "\u2026" : "";
34666
34677
  }
34667
34678
  const summary = `<string, ${value.length} characters; preview size-limited>`;
34668
34679
  const rendered = appendWithinBudget(summary, formatPreview("preview", value, limits, summary), limits);
34669
34680
  if (rendered) return rendered;
34670
34681
  if (fits(summary, limits)) return summary;
34671
- return fits("…", limits) ? "…" : "";
34682
+ return fits("\u2026", limits) ? "\u2026" : "";
34672
34683
  }
34673
34684
  const outline = [];
34674
34685
  const previews = [];
@@ -34912,24 +34923,24 @@ function formatToolResultForObserver(value, options) {
34912
34923
  const OBSERVER_EXTRACTION_INSTRUCTIONS = `CRITICAL: DISTINGUISH USER ASSERTIONS FROM QUESTIONS
34913
34924
 
34914
34925
  When the user TELLS you something about themselves, mark it as an assertion:
34915
- - "I have two kids" → 🔴 (14:30) User stated has two kids
34916
- - "I work at Acme Corp" → 🔴 (14:31) User stated works at Acme Corp
34917
- - "I graduated in 2019" → 🔴 (14:32) User stated graduated in 2019
34926
+ - "I have two kids" \u2192 \u{1F534} (14:30) User stated has two kids
34927
+ - "I work at Acme Corp" \u2192 \u{1F534} (14:31) User stated works at Acme Corp
34928
+ - "I graduated in 2019" \u2192 \u{1F534} (14:32) User stated graduated in 2019
34918
34929
 
34919
34930
  When the user ASKS about something, mark it as a question/request:
34920
- - "Can you help me with X?" → 🔴 (15:00) User asked help with X
34921
- - "What's the best way to do Y?" → 🔴 (15:01) User asked best way to do Y
34931
+ - "Can you help me with X?" \u2192 \u{1F534} (15:00) User asked help with X
34932
+ - "What's the best way to do Y?" \u2192 \u{1F534} (15:01) User asked best way to do Y
34922
34933
 
34923
34934
  Distinguish between QUESTIONS and STATEMENTS OF INTENT:
34924
- - "Can you recommend..." → Question (extract as "User asked...")
34925
- - "I'm looking forward to [doing X]" → Statement of intent (extract as "User stated they will [do X] (include estimated/actual date if mentioned)")
34926
- - "I need to [do X]" → Statement of intent (extract as "User stated they need to [do X] (again, add date if mentioned)")
34935
+ - "Can you recommend..." \u2192 Question (extract as "User asked...")
34936
+ - "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)")
34937
+ - "I need to [do X]" \u2192 Statement of intent (extract as "User stated they need to [do X] (again, add date if mentioned)")
34927
34938
 
34928
34939
  STATE CHANGES AND UPDATES:
34929
34940
  When a user indicates they are changing something, frame it as a state change that supersedes previous information:
34930
- - "I'm going to start doing X instead of Y" → "User will start doing X (changing from Y)"
34931
- - "I'm switching from A to B" → "User is switching from A to B"
34932
- - "I moved my stuff to the new place" → "User moved their stuff to the new place (no longer at previous location)"
34941
+ - "I'm going to start doing X instead of Y" \u2192 "User will start doing X (changing from Y)"
34942
+ - "I'm switching from A to B" \u2192 "User is switching from A to B"
34943
+ - "I moved my stuff to the new place" \u2192 "User moved their stuff to the new place (no longer at previous location)"
34933
34944
 
34934
34945
  If the new state contradicts or updates previous information, make that explicit:
34935
34946
  - BAD: "User plans to use the new method"
@@ -35020,11 +35031,11 @@ BAD: User got something.
35020
35031
  GOOD: User purchased / received / was given something. (be specific)
35021
35032
 
35022
35033
  Common clarifications:
35023
- - "getting" something regularly → "subscribed to" or "enrolled in"
35024
- - "getting" something once → "purchased" or "acquired"
35025
- - "got" → "purchased", "received as gift", "was given", "picked up"
35026
- - "signed up" → "enrolled in", "registered for", "subscribed to"
35027
- - "stopped getting" → "canceled", "unsubscribed from", "discontinued"
35034
+ - "getting" something regularly \u2192 "subscribed to" or "enrolled in"
35035
+ - "getting" something once \u2192 "purchased" or "acquired"
35036
+ - "got" \u2192 "purchased", "received as gift", "was given", "picked up"
35037
+ - "signed up" \u2192 "enrolled in", "registered for", "subscribed to"
35038
+ - "stopped getting" \u2192 "canceled", "unsubscribed from", "discontinued"
35028
35039
 
35029
35040
  When the assistant interprets or confirms the user's vague language, prefer the assistant's precise terminology.
35030
35041
 
@@ -35109,16 +35120,16 @@ AVOIDING REPETITIVE OBSERVATIONS:
35109
35120
  - Do NOT repeat the same observation across multiple turns if there is no new information.
35110
35121
  - 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.
35111
35122
 
35112
- Example — BAD (repetitive):
35113
- * 🟡 (14:30) Agent used view tool on src/auth.ts
35114
- * 🟡 (14:31) Agent used view tool on src/users.ts
35115
- * 🟡 (14:32) Agent used view tool on src/routes.ts
35123
+ Example \u2014 BAD (repetitive):
35124
+ * \u{1F7E1} (14:30) Agent used view tool on src/auth.ts
35125
+ * \u{1F7E1} (14:31) Agent used view tool on src/users.ts
35126
+ * \u{1F7E1} (14:32) Agent used view tool on src/routes.ts
35116
35127
 
35117
- Example — GOOD (grouped):
35118
- * 🟡 (14:30) Agent browsed source files for auth flow
35119
- * -> viewed src/auth.ts — found token validation logic
35120
- * -> viewed src/users.ts — found user lookup by email
35121
- * -> viewed src/routes.ts — found middleware chain
35128
+ Example \u2014 GOOD (grouped):
35129
+ * \u{1F7E1} (14:30) Agent browsed source files for auth flow
35130
+ * -> viewed src/auth.ts \u2014 found token validation logic
35131
+ * -> viewed src/users.ts \u2014 found user lookup by email
35132
+ * -> viewed src/routes.ts \u2014 found middleware chain
35122
35133
 
35123
35134
  Only add a new observation for a repeated action if the NEW result changes the picture.
35124
35135
 
@@ -35131,29 +35142,29 @@ COMPLETION TRACKING:
35131
35142
  Completion observations are not just summaries. They are explicit memory signals to the assistant that a task, question, or subtask has been resolved.
35132
35143
  Without clear completion markers, the assistant may forget that work is already finished and may repeat, reopen, or continue an already-completed task.
35133
35144
 
35134
- Use ✅ to answer: "What exactly is now done?"
35145
+ Use \u2705 to answer: "What exactly is now done?"
35135
35146
  Choose completion observations that help the assistant know what is finished and should not be reworked unless new information appears.
35136
35147
 
35137
- Use ✅ when:
35148
+ Use \u2705 when:
35138
35149
  - The user explicitly confirms something worked or was answered ("thanks, that fixed it", "got it", "perfect")
35139
35150
  - The assistant provided a definitive, complete answer to a factual question and the user moved on
35140
35151
  - A multi-step task reached its stated goal
35141
35152
  - The user acknowledged receipt of requested information
35142
35153
  - A concrete subtask, fix, deliverable, or implementation step became complete during ongoing work
35143
35154
 
35144
- Do NOT use ✅ when:
35145
- - The assistant merely responded — the user might follow up with corrections
35155
+ Do NOT use \u2705 when:
35156
+ - The assistant merely responded \u2014 the user might follow up with corrections
35146
35157
  - The topic is paused but not resolved ("I'll try that later")
35147
35158
  - The user's reaction is ambiguous
35148
35159
 
35149
35160
  FORMAT:
35150
35161
  As a sub-bullet under the related observation group:
35151
- * 🔴 (14:30) User asked how to configure auth middleware
35162
+ * \u{1F534} (14:30) User asked how to configure auth middleware
35152
35163
  * -> Agent explained JWT setup with code example
35153
- * ✅ User confirmed auth is working
35164
+ * \u2705 User confirmed auth is working
35154
35165
 
35155
35166
  Or as a standalone observation when closing out a broader task:
35156
- * ✅ (14:45) Auth configuration task completed — user confirmed middleware is working
35167
+ * \u2705 (14:45) Auth configuration task completed \u2014 user confirmed middleware is working
35157
35168
 
35158
35169
  Completion observations should be terse but specific about WHAT was completed.
35159
35170
  Prefer concrete resolved outcomes over abstract workflow status so the assistant remembers what is already done.`;
@@ -35170,28 +35181,28 @@ buildObserverOutputFormat();
35170
35181
  */
35171
35182
  function buildObserverOutputFormat(extractors) {
35172
35183
  return `Use priority levels:
35173
- - 🔴 High: explicit user facts, preferences, unresolved goals, critical context
35174
- - 🟡 Medium: project details, learned information, tool results
35175
- - 🟢 Low: minor details, uncertain observations
35176
- - ✅ Completed: concrete task finished, question answered, issue resolved, goal achieved, or subtask completed in a way that helps the assistant know it is done
35184
+ - \u{1F534} High: explicit user facts, preferences, unresolved goals, critical context
35185
+ - \u{1F7E1} Medium: project details, learned information, tool results
35186
+ - \u{1F7E2} Low: minor details, uncertain observations
35187
+ - \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
35177
35188
 
35178
35189
  Group related observations (like tool sequences) by indenting:
35179
- * 🔴 (14:33) Agent debugging auth issue
35190
+ * \u{1F534} (14:33) Agent debugging auth issue
35180
35191
  * -> ran git status, found 3 modified files
35181
35192
  * -> viewed auth.ts:45-60, found missing null check
35182
35193
  * -> applied fix, tests now pass
35183
- * ✅ Tests passing, auth issue resolved
35194
+ * \u2705 Tests passing, auth issue resolved
35184
35195
 
35185
35196
  Group observations by date. Within a date, list observations in the order the events happened (not by importance), each with 24-hour time.
35186
35197
 
35187
35198
  <observations>
35188
35199
  Date: Dec 4, 2025
35189
- * 🔴 (14:30) User prefers direct answers
35190
- * 🔴 (14:31) Working on feature X
35191
- * 🟡 (14:32) User might prefer dark mode
35200
+ * \u{1F534} (14:30) User prefers direct answers
35201
+ * \u{1F534} (14:31) Working on feature X
35202
+ * \u{1F7E1} (14:32) User might prefer dark mode
35192
35203
 
35193
35204
  Date: Dec 5, 2025
35194
- * 🔴 (09:15) Continued work on feature X
35205
+ * \u{1F534} (09:15) Continued work on feature X
35195
35206
  </observations>
35196
35207
 
35197
35208
  ${buildExtractorOutputSections(extractors ?? []) || (extractors === void 0 ? `
@@ -35221,9 +35232,9 @@ const OBSERVER_GUIDELINES = `- Be specific enough for the assistant to act on
35221
35232
  - If the agent calls tools, observe what was called, why, and what was learned
35222
35233
  - When observing files with line numbers, include the line number if useful
35223
35234
  - If the agent provides a detailed response, observe the contents so it could be repeated
35224
- - Make sure you start each observation with a priority emoji (🔴, 🟡, 🟢) or a completion marker (✅)
35225
- - 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 🔴
35226
- - Treat ✅ as a memory signal that tells the assistant something is finished and should not be repeated unless new information changes it
35235
+ - Make sure you start each observation with a priority emoji (\u{1F534}, \u{1F7E1}, \u{1F7E2}) or a completion marker (\u2705)
35236
+ - 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}
35237
+ - Treat \u2705 as a memory signal that tells the assistant something is finished and should not be repeated unless new information changes it
35227
35238
  - Make completion observations answer "What exactly is now done?"
35228
35239
  - Prefer concrete resolved outcomes over meta-level workflow or bookkeeping updates
35229
35240
  - When multiple concrete things were completed, capture the concrete completed work rather than collapsing it into a vague progress summary
@@ -35277,8 +35288,8 @@ For multi-thread output, wrap each thread's observations like this:
35277
35288
  <observations>
35278
35289
  <thread id="thread_id_1">
35279
35290
  Date: Dec 4, 2025
35280
- * 🔴 (14:30) User prefers direct answers
35281
- * 🔴 (14:31) Working on feature X${currentTaskEnabled ? `
35291
+ * \u{1F534} (14:30) User prefers direct answers
35292
+ * \u{1F534} (14:31) Working on feature X${currentTaskEnabled ? `
35282
35293
 
35283
35294
  <current-task>
35284
35295
  What the agent is currently working on in this thread
@@ -35291,7 +35302,7 @@ Hint for the agent's next message in this thread
35291
35302
 
35292
35303
  <thread id="thread_id_2">
35293
35304
  Date: Dec 5, 2025
35294
- * 🔴 (09:15) User asked about deployment${currentTaskEnabled ? `
35305
+ * \u{1F534} (09:15) User asked about deployment${currentTaskEnabled ? `
35295
35306
 
35296
35307
  <current-task>
35297
35308
  Current task for this thread
@@ -36122,7 +36133,7 @@ function sanitizeObservationLines(observations) {
36122
36133
  const lines = observations.split("\n");
36123
36134
  let changed = false;
36124
36135
  for (let i = 0; i < lines.length; i++) if (lines[i].length > MAX_OBSERVATION_LINE_CHARS) {
36125
- lines[i] = safeSlice(lines[i], MAX_OBSERVATION_LINE_CHARS) + " … [truncated]";
36136
+ lines[i] = safeSlice(lines[i], MAX_OBSERVATION_LINE_CHARS) + " \u2026 [truncated]";
36126
36137
  changed = true;
36127
36138
  }
36128
36139
  return changed ? lines.join("\n") : observations;
@@ -36320,8 +36331,8 @@ function describeDegenerateOutput(text, snippetChars = 400) {
36320
36331
  */
36321
36332
  function optimizeObservationsForContext(observations) {
36322
36333
  let optimized = stripEphemeralAnchorIds(observations);
36323
- optimized = optimized.replace(/🟡\s*/g, "");
36324
- optimized = optimized.replace(/🟢\s*/g, "");
36334
+ optimized = optimized.replace(/\uD83D\uDFE1\s*/g, "");
36335
+ optimized = optimized.replace(/\uD83D\uDFE2\s*/g, "");
36325
36336
  optimized = optimized.replace(/\s*->\s*/g, " ");
36326
36337
  optimized = optimized.replace(/ +/g, " ");
36327
36338
  optimized = optimized.replace(/\n{3,}/g, "\n\n");
@@ -37277,7 +37288,7 @@ async function resolveImageDimensionsAsync(part) {
37277
37288
  const url = resolveHttpAssetUrl(getObjectValue(part, "image") ?? getObjectValue(part, "data"));
37278
37289
  if (!url) return existing;
37279
37290
  try {
37280
- const probeImageSize = (await import("./probe-image-size-C0BvSeqt.js").then((m) => /* @__PURE__ */ __toESM$1(m.default, 1))).default;
37291
+ const probeImageSize = (await import("./probe-image-size-DZvSdjzK.js").then((m) => /* @__PURE__ */ __toESM$1(m.default, 1))).default;
37281
37292
  const probed = await probeImageSize(url, {
37282
37293
  open_timeout: REMOTE_IMAGE_PROBE_TIMEOUT_MS,
37283
37294
  response_timeout: REMOTE_IMAGE_PROBE_TIMEOUT_MS,
@@ -38599,8 +38610,8 @@ const updateWorkingMemoryTool = (memoryConfig) => {
38599
38610
  }
38600
38611
  const usesMergeSemantics = Boolean(schema);
38601
38612
  const useStateSignals = memoryConfig?.workingMemory?.useStateSignals === true;
38602
- 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.`;
38603
- 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.`;
38613
+ 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.`;
38614
+ 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.`;
38604
38615
  return createTool({
38605
38616
  id: "update-working-memory",
38606
38617
  description,
@@ -39610,8 +39621,8 @@ async function pageGroups({ om, threadId, resourceId, groupId, recordId, directi
39610
39621
  })).count > 0;
39611
39622
  const hasLater = direction === "before" || hasMore;
39612
39623
  const newer = hasLater ? null : await newerMessagesNote(page.at(-1).group, countNewerMessages, pagingThreadId);
39613
- text.unshift(hasEarlier ? `— Browse earlier: ${pagingCall(page[0].group.id, "before", pagingThreadId, page[0].record.id)} —` : "— Start of retained observation history for this thread. —");
39614
- 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. —");
39624
+ 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");
39625
+ 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");
39615
39626
  text.unshift(`### Observation page\nThread: ${threadTitle || "(untitled)"}\nShowing ${page.length} groups ${requestedDirection === void 0 ? "starting at" : `strictly ${direction}`} \`${groupId}\` (oldest first).`);
39616
39627
  return {
39617
39628
  results: text.join("\n\n"),
@@ -39797,7 +39808,7 @@ async function listThreadsForResource({ memory, resourceId, currentThreadId, pag
39797
39808
  const title = thread.title || "(untitled)";
39798
39809
  const updated = formatTimestamp(thread.updatedAt);
39799
39810
  const created = formatTimestamp(thread.createdAt);
39800
- const marker = isCurrent ? " ← current" : "";
39811
+ const marker = isCurrent ? " \u2190 current" : "";
39801
39812
  lines.push(`- **${title}**${marker}`);
39802
39813
  lines.push(` id: ${thread.id}`);
39803
39814
  lines.push(` updated: ${updated} | created: ${created}`);
@@ -39976,7 +39987,7 @@ async function searchMessagesForResource({ memory, om, resourceId, currentThread
39976
39987
  const groupLine = match.groupId ? `- observation group: ${groupCursor(match.groupId, match.recordId)}` : void 0;
39977
39988
  const scoreLine = `- score: ${match.score.toFixed(2)}`;
39978
39989
  const prev = i > 0 ? ordered[i - 1].match : void 0;
39979
- 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)} —`);
39990
+ 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`);
39980
39991
  if (suppression) {
39981
39992
  sections.push(`${groupLine}\n thread: ${match.threadId}; ${suppression}`);
39982
39993
  continue;
@@ -40531,7 +40542,7 @@ async function recallAttachmentView({ memory, threadId, resourceId, cursor, part
40531
40542
  const partType = rawPart?.type;
40532
40543
  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.` };
40533
40544
  const resolvedAttachment = resolveViewableAttachment(rawPart);
40534
- if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)} — ${resolvedAttachment.note}` };
40545
+ if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)} \u2014 ${resolvedAttachment.note}` };
40535
40546
  return { content: [{
40536
40547
  type: "text",
40537
40548
  text: formatAttachmentPart(partType, rawPart)
@@ -40934,7 +40945,7 @@ const recallTool = (_memoryConfig, options) => {
40934
40945
  if (!thread) return { error: "Could not resolve current thread." };
40935
40946
  if (isResourceScope && resourceId && thread.resourceId !== resourceId) throw new Error("Thread does not belong to the active resource");
40936
40947
  return {
40937
- threads: `- **${thread.title || "(untitled)"}** ← current\n id: ${thread.id}\n updated: ${formatTimestamp(thread.updatedAt)} | created: ${formatTimestamp(thread.createdAt)}`,
40948
+ threads: `- **${thread.title || "(untitled)"}** \u2190 current\n id: ${thread.id}\n updated: ${formatTimestamp(thread.updatedAt)} | created: ${formatTimestamp(thread.createdAt)}`,
40938
40949
  count: 1,
40939
40950
  page: 0,
40940
40951
  hasMore: false
@@ -41497,6 +41508,79 @@ var BufferingCoordinator = class BufferingCoordinator {
41497
41508
  * Key format: "refl:{lockKey}"
41498
41509
  */
41499
41510
  static reflectionBufferCycleIds = /* @__PURE__ */ new Map();
41511
+ /**
41512
+ * The buffered-reflection op that set the reflection boundary and cycle, and the generation
41513
+ * it buffers for. Key format: "refl:{lockKey}"
41514
+ */
41515
+ static reflectionBufferOwners = /* @__PURE__ */ new Map();
41516
+ /** Set the reflection boundary for a new buffered-reflection op on generation `recordId`. */
41517
+ static startReflectionBuffer(bufferKey, tokens, recordId) {
41518
+ const owner = {
41519
+ recordId,
41520
+ retired: false
41521
+ };
41522
+ BufferingCoordinator.lastBufferedBoundary.set(bufferKey, tokens);
41523
+ BufferingCoordinator.reflectionBufferOwners.set(bufferKey, owner);
41524
+ return owner;
41525
+ }
41526
+ /** Drop this process's reflection boundary, cycle, and owner. */
41527
+ static clearReflectionBuffer(bufferKey) {
41528
+ BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
41529
+ BufferingCoordinator.reflectionBufferCycleIds.delete(bufferKey);
41530
+ BufferingCoordinator.reflectionBufferOwners.delete(bufferKey);
41531
+ }
41532
+ /**
41533
+ * Another writer retired generation `recordId`, so a buffer this process prepared for it can
41534
+ * never activate. Its boundary and cycle are dropped now, or, while the op that set them is
41535
+ * still running (it may be awaiting its `onReflectionEnd` hook), when that op finishes. State
41536
+ * owned by a newer generation is kept.
41537
+ */
41538
+ static retireReflectionBuffer(bufferKey, recordId) {
41539
+ const owner = BufferingCoordinator.reflectionBufferOwners.get(bufferKey);
41540
+ if (owner && owner.recordId !== recordId) return;
41541
+ if (owner && BufferingCoordinator.asyncBufferingOps.has(bufferKey)) {
41542
+ owner.retired = true;
41543
+ return;
41544
+ }
41545
+ BufferingCoordinator.clearReflectionBuffer(bufferKey);
41546
+ }
41547
+ /**
41548
+ * Reconcile this process's reflection buffer state against an observed head record.
41549
+ * Whenever `head.id` differs from `owner.recordId`, confirm against a fresh storage read started
41550
+ * after `owner` existed (never trusting `generationCount`, which resets to 0 after `clear()`):
41551
+ * only retire/clear when storage's live head is no longer `owner.recordId`.
41552
+ */
41553
+ static async reconcileReflectionBufferHead(bufferKey, headId, readLiveHead) {
41554
+ const owner = BufferingCoordinator.reflectionBufferOwners.get(bufferKey);
41555
+ if (!owner || owner.recordId === headId) return;
41556
+ const ownerRecordId = owner.recordId;
41557
+ const live = await readLiveHead();
41558
+ if (BufferingCoordinator.reflectionBufferOwners.get(bufferKey) !== owner || owner.recordId !== ownerRecordId) return;
41559
+ if (live?.id === ownerRecordId) return;
41560
+ if (BufferingCoordinator.asyncBufferingOps.has(bufferKey)) {
41561
+ owner.retired = true;
41562
+ return;
41563
+ }
41564
+ BufferingCoordinator.clearReflectionBuffer(bufferKey);
41565
+ }
41566
+ /**
41567
+ * Take the buffered-reflection cycle id for generation `recordId` and release its
41568
+ * coordinator state after its buffer activates. State owned by another generation
41569
+ * is left untouched.
41570
+ */
41571
+ static consumeReflectionBuffer(bufferKey, recordId) {
41572
+ const owner = BufferingCoordinator.reflectionBufferOwners.get(bufferKey);
41573
+ if (owner && owner.recordId !== recordId) return void 0;
41574
+ const cycleId = BufferingCoordinator.reflectionBufferCycleIds.get(bufferKey);
41575
+ if (owner && BufferingCoordinator.asyncBufferingOps.has(bufferKey)) owner.retired = true;
41576
+ else BufferingCoordinator.clearReflectionBuffer(bufferKey);
41577
+ return cycleId;
41578
+ }
41579
+ /** Called when the op that started as `owner` finishes; completes a deferred retirement. */
41580
+ static finishReflectionBuffer(bufferKey, owner) {
41581
+ if (BufferingCoordinator.reflectionBufferOwners.get(bufferKey) !== owner) return;
41582
+ if (owner.retired) BufferingCoordinator.clearReflectionBuffer(bufferKey);
41583
+ }
41500
41584
  constructor(opts) {
41501
41585
  this.observationConfig = opts.observationConfig;
41502
41586
  this.reflectionConfig = opts.reflectionConfig;
@@ -41552,6 +41636,7 @@ var BufferingCoordinator = class BufferingCoordinator {
41552
41636
  BufferingCoordinator.asyncBufferingOps.delete(obsBufKey);
41553
41637
  BufferingCoordinator.asyncBufferingOps.delete(reflBufKey);
41554
41638
  BufferingCoordinator.reflectionBufferCycleIds.delete(reflBufKey);
41639
+ BufferingCoordinator.reflectionBufferOwners.delete(reflBufKey);
41555
41640
  }
41556
41641
  }
41557
41642
  /**
@@ -41611,9 +41696,9 @@ const suggestedResponseInstructions = `Hint for the agent's immediate next messa
41611
41696
  - "The assistant should wait for the user to respond before continuing."
41612
41697
  - Call the view tool on src/example.ts to continue debugging.`;
41613
41698
  const threadTitleInstructions = `A short, noun-phrase title for this conversation (2-5 words). Examples:
41614
- - "Auth bug fix" — not "Fixing the auth bug"
41615
- - "Dark mode toggle" — not "User wants dark mode toggle added"
41616
- - "Deployment pipeline setup" — not "Setting up deployment pipeline for project"
41699
+ - "Auth bug fix" \u2014 not "Fixing the auth bug"
41700
+ - "Dark mode toggle" \u2014 not "User wants dark mode toggle added"
41701
+ - "Deployment pipeline setup" \u2014 not "Setting up deployment pipeline for project"
41617
41702
  Only update when the topic meaningfully changes.`;
41618
41703
  function createCurrentTaskExtractor() {
41619
41704
  return new Extractor({
@@ -42683,7 +42768,7 @@ var SyncObservationStrategy = class extends ObservationStrategy {
42683
42768
  failures: result.extractionFailures,
42684
42769
  previousValues: this.priorExtractedValues,
42685
42770
  rawObservations: result.observations,
42686
- recentMessages: formatMessagesForObserver(this.opts.messages, {
42771
+ recentMessages: () => formatMessagesForObserver(this.opts.messages, {
42687
42772
  maxPartLength: 500,
42688
42773
  timeZone: this.opts.record.observedTimezone
42689
42774
  }),
@@ -42907,7 +42992,7 @@ var AsyncBufferObservationStrategy = class extends ObservationStrategy {
42907
42992
  failures: result.extractionFailures,
42908
42993
  previousValues: this.priorExtractedValues,
42909
42994
  rawObservations: result.observations,
42910
- recentMessages: formatMessagesForObserver(messages, {
42995
+ recentMessages: () => formatMessagesForObserver(messages, {
42911
42996
  maxPartLength: 500,
42912
42997
  timeZone: this.opts.record.observedTimezone
42913
42998
  }),
@@ -43336,7 +43421,7 @@ var ResourceScopedObservationStrategy = class extends ObservationStrategy {
43336
43421
  failures: result.extractionFailures,
43337
43422
  previousValues,
43338
43423
  rawObservations: result.observations,
43339
- recentMessages: formatMessagesForObserver(threadMessages, {
43424
+ recentMessages: () => formatMessagesForObserver(threadMessages, {
43340
43425
  maxPartLength: 500,
43341
43426
  timeZone: this.opts.record.observedTimezone
43342
43427
  }),
@@ -43665,7 +43750,7 @@ var ObservationStep = class {
43665
43750
  }
43666
43751
  /** Step context from prepare(). Throws if prepare() hasn't been called. */
43667
43752
  get context() {
43668
- if (!this._context) throw new Error("Step not prepared yet — call prepare() first");
43753
+ if (!this._context) throw new Error("Step not prepared yet \u2014 call prepare() first");
43669
43754
  return this._context;
43670
43755
  }
43671
43756
  /**
@@ -44085,7 +44170,7 @@ var ObservationStep = class {
44085
44170
  const messagesToSeal = messageToSeal ? [messageToSeal] : [];
44086
44171
  this.turn.abortSignal?.throwIfAborted();
44087
44172
  om.sealMessagesForBuffering(messagesToSeal);
44088
- if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation — step-0 seeded response message holds the active id");
44173
+ if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation \u2014 step-0 seeded response message holds the active id");
44089
44174
  else try {
44090
44175
  await this.turn.hooks?.onSyncObservationComplete?.();
44091
44176
  } catch (error) {
@@ -44235,12 +44320,12 @@ var ObservationTurn = class {
44235
44320
  messageList;
44236
44321
  /** The current cached record. Refreshed after mutations (activate/observe/reflect). */
44237
44322
  get record() {
44238
- if (!this._record) throw new Error("Turn not started — call start() first");
44323
+ if (!this._record) throw new Error("Turn not started \u2014 call start() first");
44239
44324
  return this._record;
44240
44325
  }
44241
44326
  /** The context loaded during start(). */
44242
44327
  get context() {
44243
- if (!this._context) throw new Error("Turn not started — call start() first");
44328
+ if (!this._context) throw new Error("Turn not started \u2014 call start() first");
44244
44329
  return this._context;
44245
44330
  }
44246
44331
  /** Whether the turn has been ended and can no longer accept steps. */
@@ -44309,7 +44394,7 @@ var ObservationTurn = class {
44309
44394
  * (its output messages will be saved at the start of the new step's prepare()).
44310
44395
  */
44311
44396
  step(stepNumber) {
44312
- if (!this._started) throw new Error("Turn not started — call start() first");
44397
+ if (!this._started) throw new Error("Turn not started \u2014 call start() first");
44313
44398
  if (this._ended) throw new Error("Turn already ended");
44314
44399
  this._currentStep = new ObservationStep(this, stepNumber);
44315
44400
  return this._currentStep;
@@ -44404,6 +44489,79 @@ var ObservationTurn = class {
44404
44489
  };
44405
44490
  }
44406
44491
  };
44492
+ const pendingValuesBaseSchema = z$2.object({
44493
+ recordId: z$2.string(),
44494
+ reflectedObservationLineCount: z$2.number(),
44495
+ values: z$2.record(z$2.string(), z$2.unknown())
44496
+ });
44497
+ const pendingValuesSchema = z$2.union([pendingValuesBaseSchema.extend({
44498
+ reflectionDigest: z$2.string().regex(/^[a-f0-9]{64}$/),
44499
+ reflection: z$2.never().optional()
44500
+ }), pendingValuesBaseSchema.extend({
44501
+ reflection: z$2.string(),
44502
+ reflectionDigest: z$2.never().optional()
44503
+ })]);
44504
+ const metadataSchema = z$2.record(z$2.string(), z$2.unknown());
44505
+ function reflectionDigest(reflection) {
44506
+ return createHash("sha256").update(reflection).digest("hex");
44507
+ }
44508
+ function getMastraMetadata(metadata) {
44509
+ const parsed = metadataSchema.safeParse(metadata?.mastra);
44510
+ return parsed.success ? parsed.data : {};
44511
+ }
44512
+ /** Keep prepared values outside active OM metadata, durable across Memory instances. */
44513
+ async function stageBufferedReflectionValues(storage, record, values) {
44514
+ if (!record.threadId || !record.bufferedReflection) return;
44515
+ const digest = reflectionDigest(record.bufferedReflection);
44516
+ await storage.updateThreadMetadata({
44517
+ id: record.threadId,
44518
+ update: (thread) => ({
44519
+ ...thread.metadata,
44520
+ mastra: {
44521
+ ...getMastraMetadata(thread.metadata),
44522
+ omBufferedReflection: {
44523
+ recordId: record.id,
44524
+ reflectionDigest: digest,
44525
+ reflectedObservationLineCount: record.reflectedObservationLineCount ?? 0,
44526
+ values: values ?? {}
44527
+ }
44528
+ }
44529
+ })
44530
+ });
44531
+ }
44532
+ /** Called under the OM commit lock, only after this exact buffer was activated. */
44533
+ async function publishBufferedReflectionValues(storage, extractors, record) {
44534
+ if (!record.threadId || !record.bufferedReflection) return;
44535
+ const digest = reflectionDigest(record.bufferedReflection);
44536
+ await storage.updateThreadMetadata({
44537
+ id: record.threadId,
44538
+ update: (thread) => {
44539
+ const mastra = getMastraMetadata(thread.metadata);
44540
+ const parsed = pendingValuesSchema.safeParse(mastra.omBufferedReflection);
44541
+ if (!parsed.success) return;
44542
+ const pending = parsed.data;
44543
+ if (pending.recordId !== record.id || (pending.reflectionDigest !== void 0 ? pending.reflectionDigest !== digest : pending.reflection !== record.bufferedReflection) || pending.reflectedObservationLineCount !== (record.reflectedObservationLineCount ?? 0)) return;
44544
+ const update = buildThreadMetadataFromExtractedValues(extractors, pending.values);
44545
+ const previous = getThreadOMMetadata(thread.metadata);
44546
+ const metadata = setThreadOMMetadata(thread.metadata, {
44547
+ currentTask: update.currentTask ?? previous?.currentTask,
44548
+ suggestedResponse: update.suggestedResponse ?? previous?.suggestedResponse,
44549
+ threadTitle: update.threadTitle ?? previous?.threadTitle,
44550
+ extracted: {
44551
+ ...previous?.extracted,
44552
+ ...update.extracted
44553
+ }
44554
+ });
44555
+ return {
44556
+ ...metadata,
44557
+ mastra: {
44558
+ ...getMastraMetadata(metadata),
44559
+ omBufferedReflection: null
44560
+ }
44561
+ };
44562
+ }
44563
+ });
44564
+ }
44407
44565
  /**
44408
44566
  * Build the Reflector's system prompt.
44409
44567
  *
@@ -44457,8 +44615,8 @@ When consolidating observations:
44457
44615
  - 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
44458
44616
  - Prefer many short factual lines over prose summaries. Do not replace facts with generalities like "discussed travel plans"
44459
44617
  - Combine related items where it makes sense (e.g., "agent called view tool 5 times on file x")
44460
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44461
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
44618
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44619
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
44462
44620
  - Condense the wording of older observations more than recent ones, but keep their facts
44463
44621
 
44464
44622
  CRITICAL: USER ASSERTIONS vs QUESTIONS
@@ -44480,23 +44638,23 @@ When observations contain <thread id="..."> sections:
44480
44638
  Example input:
44481
44639
  <thread id="thread-1">
44482
44640
  Date: Dec 4, 2025
44483
- * 🔴 (14:30) User prefers TypeScript
44484
- * 🟡 (14:35) Working on auth feature
44641
+ * \u{1F534} (14:30) User prefers TypeScript
44642
+ * \u{1F7E1} (14:35) Working on auth feature
44485
44643
  </thread>
44486
44644
  <thread id="thread-2">
44487
44645
  Date: Dec 4, 2025
44488
- * 🔴 (15:00) User prefers TypeScript
44489
- * 🟡 (15:05) Debugging API endpoint
44646
+ * \u{1F534} (15:00) User prefers TypeScript
44647
+ * \u{1F7E1} (15:05) Debugging API endpoint
44490
44648
  </thread>
44491
44649
 
44492
44650
  Example output (consolidated):
44493
44651
  Date: Dec 4, 2025
44494
- * 🔴 (14:30) User prefers TypeScript
44652
+ * \u{1F534} (14:30) User prefers TypeScript
44495
44653
  <thread id="thread-1">
44496
- * 🟡 (14:35) Working on auth feature
44654
+ * \u{1F7E1} (14:35) Working on auth feature
44497
44655
  </thread>
44498
44656
  <thread id="thread-2">
44499
- * 🟡 (15:05) Debugging API endpoint
44657
+ * \u{1F7E1} (15:05) Debugging API endpoint
44500
44658
  </thread>
44501
44659
 
44502
44660
  === OUTPUT FORMAT ===
@@ -44527,8 +44685,8 @@ Please re-process with slightly more compression:
44527
44685
  - Memory is getting long - use a more condensed style throughout
44528
44686
  - Combine related items more aggressively but do not lose important specific details of names, places, events, and people
44529
44687
  - 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
44530
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44531
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
44688
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44689
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
44532
44690
 
44533
44691
  Aim for a 8/10 detail level.
44534
44692
  `,
@@ -44544,8 +44702,8 @@ Please re-process with much more aggressive compression:
44544
44702
  - Combine related items aggressively but do not lose important specific details of names, places, events, and people
44545
44703
  - 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
44546
44704
  - If the same file or module is mentioned across many observations, merge into one entry covering the full arc
44547
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44548
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
44705
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44706
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
44549
44707
  - Remove redundant information and merge overlapping observations
44550
44708
 
44551
44709
  Aim for a 6/10 detail level.
@@ -44556,14 +44714,14 @@ Aim for a 6/10 detail level.
44556
44714
  Your previous reflections have failed to compress sufficiently after multiple attempts.
44557
44715
 
44558
44716
  Please re-process with maximum compression:
44559
- - Summarize the oldest observations (first 50-70%) into brief high-level paragraphs — only key facts, decisions, and outcomes
44717
+ - Summarize the oldest observations (first 50-70%) into brief high-level paragraphs \u2014 only key facts, decisions, and outcomes
44560
44718
  - For the most recent observations (last 30-50%), retain important details but still use a condensed style
44561
- - Ruthlessly merge related observations — if 10 observations are about the same topic, combine into 1-2 lines
44562
- - Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries — drop individual steps entirely
44563
- - Drop procedural details (tool calls, retries, intermediate steps) — keep only final outcomes
44719
+ - Ruthlessly merge related observations \u2014 if 10 observations are about the same topic, combine into 1-2 lines
44720
+ - Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries \u2014 drop individual steps entirely
44721
+ - Drop procedural details (tool calls, retries, intermediate steps) \u2014 keep only final outcomes
44564
44722
  - Drop observations that are no longer relevant or have been superseded by newer information
44565
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44566
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
44723
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44724
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
44567
44725
  - Preserve: names, dates, decisions, errors, user preferences, and architectural choices
44568
44726
 
44569
44727
  Aim for a 4/10 detail level.
@@ -44574,14 +44732,14 @@ Aim for a 4/10 detail level.
44574
44732
  Multiple compression attempts have failed. The content may already be dense from a prior reflection.
44575
44733
 
44576
44734
  You MUST dramatically reduce the number of observations while keeping the standard observation format (date groups with bullet points and priority emojis):
44577
- - 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")
44578
- - Never preserve individual tool calls (viewed file X, searched for Y, ran build) — only preserve what was discovered or accomplished
44735
+ - 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")
44736
+ - Never preserve individual tool calls (viewed file X, searched for Y, ran build) \u2014 only preserve what was discovered or accomplished
44579
44737
  - Consolidate many related observations into single, more generic observations
44580
44738
  - Merge all same-day date groups into at most 2-3 date groups per day
44581
44739
  - For older content, each topic or task should be at most 1-2 observations capturing the key outcome
44582
44740
  - For recent content, retain more detail but still merge related items aggressively
44583
44741
  - If multiple observations describe incremental progress on the same task, keep only the final state
44584
- - Preserve ✅ completion markers and their outcomes but merge related completions into fewer lines
44742
+ - Preserve \u2705 completion markers and their outcomes but merge related completions into fewer lines
44585
44743
  - Preserve: user preferences, key decisions, architectural choices, and unresolved issues
44586
44744
 
44587
44745
  Aim for a 2/10 detail level. Fewer, more generic observations are better than many specific ones that exceed the budget.
@@ -44761,6 +44919,15 @@ function isReflectionApplied(returned, newRecordId, reflectedRecordId) {
44761
44919
  return returned.supersededBy === void 0 && returned.id !== reflectedRecordId;
44762
44920
  }
44763
44921
  /**
44922
+ * The active observations a buffered-reflection swap writes: the buffered reflection replaces the
44923
+ * first `reflectedLineCount` lines, and the trimmed remainder follows after a blank line. Mirrors
44924
+ * `swapBufferedReflectionToActive` in the storage adapters.
44925
+ */
44926
+ function bufferedActivationText({ bufferedReflection, observations, reflectedLineCount }) {
44927
+ const unreflected = observations.split("\n").slice(reflectedLineCount).join("\n").trim();
44928
+ return unreflected ? `${bufferedReflection}\n\n${unreflected}` : bufferedReflection;
44929
+ }
44930
+ /**
44764
44931
  * Runs the Reflector agent for compressing observations.
44765
44932
  * Handles synchronous reflection, async buffered reflection, and activation.
44766
44933
  */
@@ -44995,7 +45162,7 @@ var ReflectorRunner = class {
44995
45162
  operationType: "reflection",
44996
45163
  startedAt: streamContext.startedAt,
44997
45164
  tokensAttempted: originalTokens,
44998
- error: `Did not compress below threshold (${originalTokens} → ${reflectedTokens}, target: ${targetThreshold}), retrying at level ${currentLevel + 1}`,
45165
+ error: `Did not compress below threshold (${originalTokens} \u2192 ${reflectedTokens}, target: ${targetThreshold}), retrying at level ${currentLevel + 1}`,
44999
45166
  retrying: true,
45000
45167
  recordId: streamContext.recordId,
45001
45168
  threadId: streamContext.threadId
@@ -45025,7 +45192,7 @@ var ReflectorRunner = class {
45025
45192
  }
45026
45193
  currentLevel = Math.min(currentLevel + 1, maxLevel);
45027
45194
  }
45028
- 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`);
45195
+ 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`);
45029
45196
  const structuredExtraction = await extractStructuredValues({
45030
45197
  agent,
45031
45198
  source: "reflector",
@@ -45069,18 +45236,18 @@ var ReflectorRunner = class {
45069
45236
  startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel) {
45070
45237
  const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
45071
45238
  if (this.buffering.isAsyncBufferingInProgress(bufferKey)) return;
45072
- BufferingCoordinator.lastBufferedBoundary.set(bufferKey, observationTokens);
45239
+ const owner = BufferingCoordinator.startReflectionBuffer(bufferKey, observationTokens, record.id);
45073
45240
  registerOp(record.id, "bufferingReflection");
45074
45241
  const flagSet = this.storage.setBufferingReflectionFlag(record.id, true).catch((err) => {
45075
45242
  omError("[OM] Failed to set buffering reflection flag", err);
45076
45243
  });
45077
- const asyncOp = (async () => {
45244
+ const run = async () => {
45078
45245
  await flagSet;
45079
45246
  let outcome;
45080
45247
  let reflectionError;
45081
45248
  try {
45082
45249
  await reflectionHooks?.onReflectionStart?.();
45083
- outcome = await this.doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
45250
+ outcome = await this.doAsyncBufferedReflection(record, bufferKey, owner, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
45084
45251
  } catch (error) {
45085
45252
  reflectionError = error instanceof Error ? error : new Error(String(error));
45086
45253
  if (writer) try {
@@ -45103,7 +45270,7 @@ var ReflectorRunner = class {
45103
45270
  omError("[OM] Failed to persist buffering-failed marker after async buffered reflection failure", markerError);
45104
45271
  }
45105
45272
  omError("[OM] Async buffered reflection failed", error);
45106
- BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
45273
+ owner.retired = true;
45107
45274
  } finally {
45108
45275
  try {
45109
45276
  await reflectionHooks?.onReflectionEnd?.({
@@ -45114,13 +45281,15 @@ var ReflectorRunner = class {
45114
45281
  } catch (hookError) {
45115
45282
  omError("[OM] onReflectionEnd hook failed after async buffered reflection", hookError);
45116
45283
  }
45117
- BufferingCoordinator.asyncBufferingOps.delete(bufferKey);
45284
+ BufferingCoordinator.finishReflectionBuffer(bufferKey, owner);
45285
+ if (BufferingCoordinator.asyncBufferingOps.get(bufferKey) === asyncOp) BufferingCoordinator.asyncBufferingOps.delete(bufferKey);
45118
45286
  unregisterOp(record.id, "bufferingReflection");
45119
45287
  await this.storage.setBufferingReflectionFlag(record.id, false).catch((err) => {
45120
45288
  omError("[OM] Failed to clear buffering reflection flag", err);
45121
45289
  });
45122
45290
  }
45123
- })();
45291
+ };
45292
+ const asyncOp = run();
45124
45293
  BufferingCoordinator.asyncBufferingOps.set(bufferKey, asyncOp);
45125
45294
  this.trackBackgroundWork?.(asyncOp, lockKey);
45126
45295
  }
@@ -45128,13 +45297,27 @@ var ReflectorRunner = class {
45128
45297
  * Perform async buffered reflection — reflects observations and stores to bufferedReflection.
45129
45298
  * Does NOT create a new generation or update activeObservations.
45130
45299
  */
45131
- async doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel) {
45132
- const currentRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId) ?? record;
45300
+ async doAsyncBufferedReflection(record, bufferKey, owner, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel) {
45301
+ const freshRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
45302
+ if (BufferingCoordinator.reflectionBufferOwners.get(bufferKey) !== owner) {
45303
+ omDebug(`[OM:reflect] doAsyncBufferedReflection: ${bufferKey} was cleared while the op waited; stopping`);
45304
+ return;
45305
+ }
45306
+ const currentRecord = freshRecord ?? record;
45307
+ if (freshRecord?.bufferedReflection) {
45308
+ omDebug(`[OM:reflect] doAsyncBufferedReflection: live head ${freshRecord.id} already has a buffered reflection; skipping duplicate run`);
45309
+ owner.retired = true;
45310
+ return;
45311
+ }
45133
45312
  const observationTokens = currentRecord.observationTokenCount ?? 0;
45134
45313
  const reflectThreshold = getMaxThreshold(this.getEffectiveReflectionTokens(currentRecord));
45135
45314
  const bufferActivation = this.reflectionConfig.bufferActivation ?? .5;
45136
45315
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
45137
45316
  const cycleId = `reflect-buf-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
45317
+ if (owner.recordId !== currentRecord.id) {
45318
+ owner.recordId = currentRecord.id;
45319
+ owner.retired = false;
45320
+ }
45138
45321
  BufferingCoordinator.reflectionBufferCycleIds.set(bufferKey, cycleId);
45139
45322
  const allLines = (currentRecord.activeObservations ?? "").split("\n");
45140
45323
  const totalLines = allLines.length;
@@ -45150,7 +45333,7 @@ var ReflectorRunner = class {
45150
45333
  const reflectedObservationLineCount = linesToReflect;
45151
45334
  const sliceTokenEstimate = Math.round(avgTokensPerLine * linesToReflect);
45152
45335
  const compressionTarget = Math.round(sliceTokenEstimate * .75);
45153
- omDebug(`[OM:reflect] doAsyncBufferedReflection: slicing observations for reflection — totalLines=${totalLines}, avgTokPerLine=${avgTokensPerLine.toFixed(1)}, activationPointTokens=${activationPointTokens}, linesToReflect=${linesToReflect}/${totalLines}, sliceTokenEstimate=${sliceTokenEstimate}, compressionTarget=${compressionTarget}`);
45336
+ omDebug(`[OM:reflect] doAsyncBufferedReflection: slicing observations for reflection \u2014 totalLines=${totalLines}, avgTokPerLine=${avgTokensPerLine.toFixed(1)}, activationPointTokens=${activationPointTokens}, linesToReflect=${linesToReflect}/${totalLines}, sliceTokenEstimate=${sliceTokenEstimate}, compressionTarget=${compressionTarget}`);
45154
45337
  omDebug(`[OM:reflect] doAsyncBufferedReflection: starting reflector call, recordId=${currentRecord.id}, observationTokens=${sliceTokenEstimate}, compressionTarget=${compressionTarget} (inputTokens), activeObsLength=${activeObservations.length}, reflectedLineCount=${reflectedObservationLineCount}`);
45155
45338
  if (writer) {
45156
45339
  const startMarker = createBufferingStartMarker({
@@ -45171,10 +45354,18 @@ var ReflectorRunner = class {
45171
45354
  const compressionStartLevel = await this.getCompressionStartLevel(requestContext);
45172
45355
  const reflectResult = await this.call(activeObservations, void 0, void 0, compressionTarget, void 0, true, compressionStartLevel, requestContext, priorExtractedValues, observabilityContext, void 0, mainAgent, sendSignal, currentModel);
45173
45356
  reflectResult.observations = await applyTextTransform(this.hooks, "afterReflection", reflectResult.observations, hookContext);
45357
+ if (!reflectResult.observations.trim()) {
45358
+ omDebug(`[OM:reflect] doAsyncBufferedReflection: reflection for ${currentRecord.id} is empty after afterReflection; discarding it`);
45359
+ owner.retired = true;
45360
+ return {
45361
+ usage: reflectResult.usage,
45362
+ providerMetadata: reflectResult.providerMetadata
45363
+ };
45364
+ }
45174
45365
  const reflectionTokenCount = this.tokenCounter.countObservations(reflectResult.observations);
45175
45366
  omDebug(`[OM:reflect] doAsyncBufferedReflection: reflector returned ${reflectionTokenCount} tokens (${reflectResult.observations?.length} chars), saving to recordId=${currentRecord.id}`);
45176
45367
  if (!await runOMCommit(this.buffering.getLockKey(currentRecord.threadId, currentRecord.resourceId), async () => {
45177
- if ((await this.storage.getObservationalMemory(currentRecord.threadId, currentRecord.resourceId))?.id !== currentRecord.id) return false;
45368
+ if ((await this.storage.getObservationalMemory(currentRecord.threadId, currentRecord.resourceId))?.id !== currentRecord.id || BufferingCoordinator.reflectionBufferOwners.get(bufferKey) !== owner) return false;
45178
45369
  await this.storage.updateBufferedReflection({
45179
45370
  id: currentRecord.id,
45180
45371
  reflection: reflectResult.observations,
@@ -45182,17 +45373,18 @@ var ReflectorRunner = class {
45182
45373
  inputTokenCount: sliceTokenEstimate,
45183
45374
  reflectedObservationLineCount
45184
45375
  });
45376
+ const buffered = await this.storage.getObservationalMemory(currentRecord.threadId, currentRecord.resourceId);
45377
+ if (buffered?.id === currentRecord.id && buffered.bufferedReflection === reflectResult.observations) await stageBufferedReflectionValues(this.storage, buffered, reflectResult.extractedValues);
45185
45378
  return true;
45186
45379
  })) {
45187
45380
  omDebug(`[OM:reflect] doAsyncBufferedReflection: record ${currentRecord.id} is no longer the head; discarding the buffered reflection`);
45188
- BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
45381
+ owner.retired = true;
45189
45382
  return {
45190
45383
  usage: reflectResult.usage,
45191
45384
  providerMetadata: reflectResult.providerMetadata
45192
45385
  };
45193
45386
  }
45194
45387
  omDebug(`[OM:reflect] doAsyncBufferedReflection: bufferedReflection saved with lineCount=${reflectedObservationLineCount}`);
45195
- await persistThreadExtractedValues(this.storage, this.reflectionConfig.extractors, currentRecord.threadId ?? void 0, reflectResult.extractedValues);
45196
45388
  if (writer) {
45197
45389
  const endMarker = createBufferingEndMarker({
45198
45390
  cycleId,
@@ -45218,6 +45410,57 @@ var ReflectorRunner = class {
45218
45410
  };
45219
45411
  }
45220
45412
  /**
45413
+ * Decide what a buffered-reflection swap did. Built-in adapters only swap the buffer and line
45414
+ * count in the snapshot, return the stored record (no new generation) when another writer
45415
+ * extended them after the head check, and mark a generation they created after that check with
45416
+ * `bufferedReflectionVerified`. Adapters without that check build the new generation from
45417
+ * whatever is stored. Either way the swap must also produce what the snapshot's buffer and line
45418
+ * count give from the text the swap retired (retired records are never written again, so that
45419
+ * text is exactly what the swap read).
45420
+ *
45421
+ * Staged values are published only with the adapter's proof. Without it an extension that
45422
+ * repeats the unreflected tail produces the same text as the snapshot's buffer, so the values
45423
+ * fail closed: the activation still applies, but the staged values stay unpublished.
45424
+ */
45425
+ async classifyBufferedReflectionSwap({ result, newRecordId, snapshot, bufferedReflection, reflectedLineCount }) {
45426
+ if (result.id === snapshot.id) return {
45427
+ kind: "not-applied",
45428
+ headId: result.id
45429
+ };
45430
+ const createdByThisSwap = result.id === newRecordId;
45431
+ if (!createdByThisSwap && result.supersededBy !== void 0) return {
45432
+ kind: "not-applied",
45433
+ headId: result.id
45434
+ };
45435
+ const swapActiveObservations = result.activeObservations;
45436
+ const bufferedReflectionVerified = result.bufferedReflectionVerified === true;
45437
+ let matchesSnapshotBuffer = false;
45438
+ try {
45439
+ const retired = (await this.storage.getObservationalMemoryHistory(snapshot.threadId, snapshot.resourceId, 5, { recordId: snapshot.id })).find((candidate) => candidate.id === snapshot.id);
45440
+ matchesSnapshotBuffer = retired !== void 0 && swapActiveObservations === bufferedActivationText({
45441
+ bufferedReflection,
45442
+ observations: retired.activeObservations,
45443
+ reflectedLineCount
45444
+ });
45445
+ } catch (error) {
45446
+ omError("[OM] Failed to read the generation retired by buffered reflection activation", error);
45447
+ }
45448
+ const snapshotBufferActivated = matchesSnapshotBuffer && bufferedReflectionVerified;
45449
+ if (createdByThisSwap) return {
45450
+ kind: "applied",
45451
+ record: result,
45452
+ snapshotBufferActivated
45453
+ };
45454
+ return matchesSnapshotBuffer ? {
45455
+ kind: "applied",
45456
+ record: result,
45457
+ snapshotBufferActivated
45458
+ } : {
45459
+ kind: "not-applied",
45460
+ headId: result.id
45461
+ };
45462
+ }
45463
+ /**
45221
45464
  * Try to activate buffered reflection when threshold is reached.
45222
45465
  * Returns a discriminated result so the caller can distinguish between
45223
45466
  * "activated", "no buffer present", and "suppressed by overshoot guard"
@@ -45237,24 +45480,32 @@ var ReflectorRunner = class {
45237
45480
  }
45238
45481
  }
45239
45482
  }
45240
- const freshRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
45483
+ const storedRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
45484
+ const freshRecord = storedRecord ? { ...storedRecord } : void 0;
45241
45485
  omDebug(`[OM:reflect] tryActivateBufferedReflection: recordId=${record.id}, hasBufferedReflection=${!!freshRecord?.bufferedReflection}, bufferedReflectionLen=${freshRecord?.bufferedReflection?.length ?? 0}`);
45242
45486
  omDebug(`[OM:reflect] tryActivateBufferedReflection: freshRecord.id=${freshRecord?.id}, freshBufferedReflection=${freshRecord?.bufferedReflection ? "present (" + freshRecord.bufferedReflection.length + " chars)" : "empty"}, freshObsTokens=${freshRecord?.observationTokenCount}`);
45487
+ if (freshRecord) await BufferingCoordinator.reconcileReflectionBufferHead(bufferKey, freshRecord.id, () => this.storage.getObservationalMemory(record.threadId, record.resourceId));
45243
45488
  if (!freshRecord?.bufferedReflection) {
45244
45489
  omDebug(`[OM:reflect] tryActivateBufferedReflection: no buffered reflection after re-fetch`);
45245
45490
  return { status: "no-buffer" };
45246
45491
  }
45247
45492
  const beforeTokens = freshRecord.observationTokenCount ?? 0;
45248
45493
  const reflectedLineCount = freshRecord.reflectedObservationLineCount ?? 0;
45249
- const unreflectedLines = (freshRecord.activeObservations ?? "").split("\n").slice(reflectedLineCount);
45494
+ const currentObservations = freshRecord.activeObservations ?? "";
45495
+ const unreflectedLines = currentObservations.split("\n").slice(reflectedLineCount);
45250
45496
  const unreflectedContent = unreflectedLines.join("\n").trim();
45251
- const combinedObservations = unreflectedContent ? `${freshRecord.bufferedReflection}\n\n${unreflectedContent}` : freshRecord.bufferedReflection;
45497
+ const bufferedReflection = freshRecord.bufferedReflection;
45498
+ const combinedObservations = bufferedActivationText({
45499
+ bufferedReflection,
45500
+ observations: currentObservations,
45501
+ reflectedLineCount
45502
+ });
45252
45503
  const combinedTokenCount = this.tokenCounter.countObservations(combinedObservations);
45253
45504
  if (activationMetadata?.triggeredBy === "ttl" || activationMetadata?.triggeredBy === "provider_change") {
45254
45505
  const unreflectedTailTokens = unreflectedContent ? this.tokenCounter.countObservations(unreflectedContent) : 0;
45255
45506
  const bufferedReflectionTokens = freshRecord.bufferedReflectionTokens ?? 0;
45256
45507
  if (unreflectedTailTokens < bufferedReflectionTokens) {
45257
- omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation — unreflectedTailTokens=${unreflectedTailTokens} < bufferedReflectionTokens=${bufferedReflectionTokens}; keeping buffer for threshold activation`);
45508
+ omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation \u2014 unreflectedTailTokens=${unreflectedTailTokens} < bufferedReflectionTokens=${bufferedReflectionTokens}; keeping buffer for threshold activation`);
45258
45509
  return {
45259
45510
  status: "suppressed",
45260
45511
  reason: "composition"
@@ -45265,7 +45516,7 @@ var ReflectorRunner = class {
45265
45516
  const regularActivationTarget = reflectThreshold * (1 - bufferActivation);
45266
45517
  const minCombinedTokens = Math.round(regularActivationTarget * EARLY_ACTIVATION_SIZE_FLOOR_RATIO);
45267
45518
  if (combinedTokenCount < minCombinedTokens) {
45268
- 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`);
45519
+ 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`);
45269
45520
  return {
45270
45521
  status: "suppressed",
45271
45522
  reason: "size"
@@ -45274,28 +45525,48 @@ var ReflectorRunner = class {
45274
45525
  }
45275
45526
  omDebug(`[OM:reflect] tryActivateBufferedReflection: activating, beforeTokens=${beforeTokens}, combinedTokenCount=${combinedTokenCount}, reflectedLineCount=${reflectedLineCount}, unreflectedLines=${unreflectedLines.length}`);
45276
45527
  const newRecordId = crypto.randomUUID();
45277
- const swapped = await runOMCommit(lockKey, () => {
45528
+ const commit = await runOMCommit(lockKey, async () => {
45278
45529
  abortSignal?.throwIfAborted();
45279
- return this.storage.swapBufferedReflectionToActive({
45530
+ const head = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
45531
+ if (head && (head.id !== freshRecord.id || head.bufferedReflection !== freshRecord.bufferedReflection || head.reflectedObservationLineCount !== freshRecord.reflectedObservationLineCount)) return {
45532
+ kind: "not-applied",
45533
+ headId: head.id
45534
+ };
45535
+ const result = await this.storage.swapBufferedReflectionToActive({
45280
45536
  currentRecord: freshRecord,
45281
45537
  tokenCount: combinedTokenCount,
45282
45538
  newRecordId
45283
45539
  });
45540
+ const outcome = await this.classifyBufferedReflectionSwap({
45541
+ result,
45542
+ newRecordId,
45543
+ snapshot: freshRecord,
45544
+ bufferedReflection,
45545
+ reflectedLineCount
45546
+ });
45547
+ if (outcome.kind === "applied" && outcome.snapshotBufferActivated) try {
45548
+ await publishBufferedReflectionValues(this.storage, this.reflectionConfig.extractors, freshRecord);
45549
+ } catch (error) {
45550
+ omError("[OM] Failed to publish buffered reflection values after activation", error);
45551
+ }
45552
+ return outcome;
45284
45553
  }, {
45285
45554
  priority: "reflection",
45286
45555
  abortSignal
45287
45556
  });
45288
- if (!isReflectionApplied(swapped, newRecordId, freshRecord.id)) {
45289
- omDebug(`[OM:reflect] tryActivateBufferedReflection: buffered reflection on ${freshRecord.id} not applied (head is ${swapped.id})`);
45557
+ if (commit.kind === "not-applied") {
45558
+ omDebug(`[OM:reflect] tryActivateBufferedReflection: buffered reflection on ${freshRecord.id} not applied (head is ${commit.headId})`);
45559
+ if (commit.headId !== freshRecord.id) BufferingCoordinator.retireReflectionBuffer(bufferKey, freshRecord.id);
45290
45560
  return { status: "not-applied" };
45291
45561
  }
45292
- BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
45562
+ 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`);
45563
+ const originalCycleId = BufferingCoordinator.consumeReflectionBuffer(bufferKey, freshRecord.id);
45293
45564
  const afterRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
45294
45565
  const afterTokens = afterRecord?.observationTokenCount ?? 0;
45295
45566
  omDebug(`[OM:reflect] tryActivateBufferedReflection: activation complete! beforeTokens=${beforeTokens}, afterTokens=${afterTokens}, newRecordId=${afterRecord?.id}, newGenCount=${afterRecord?.generationCount}`);
45296
45567
  if (writer) {
45297
45568
  const activationMarker = createActivationMarker({
45298
- cycleId: BufferingCoordinator.reflectionBufferCycleIds.get(bufferKey) ?? `reflect-act-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
45569
+ cycleId: originalCycleId ?? `reflect-act-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
45299
45570
  operationType: "reflection",
45300
45571
  chunksActivated: 1,
45301
45572
  tokensActivated: beforeTokens,
@@ -45321,7 +45592,6 @@ var ReflectorRunner = class {
45321
45592
  }).catch(() => {});
45322
45593
  await this.persistMarkerToMessage(activationMarker, messageList, freshRecord.threadId ?? "", freshRecord.resourceId ?? void 0, abortSignal);
45323
45594
  }
45324
- BufferingCoordinator.reflectionBufferCycleIds.delete(bufferKey);
45325
45595
  return { status: "activated" };
45326
45596
  }
45327
45597
  /**
@@ -45338,7 +45608,7 @@ var ReflectorRunner = class {
45338
45608
  const priorExtractedValues = await getThreadExtractedValues(this.storage, this.reflectionConfig.extractors, requestedThreadId ?? record.threadId);
45339
45609
  abortSignal?.throwIfAborted();
45340
45610
  if (this.buffering.isAsyncReflectionEnabled() && observationTokens < reflectThreshold) {
45341
- if ((() => {
45611
+ if (await (async () => {
45342
45612
  if (!this.buffering.isAsyncReflectionEnabled()) return false;
45343
45613
  if (record.isBufferingReflection) {
45344
45614
  if (isOpActiveInProcess(record.id, "bufferingReflection")) return false;
@@ -45346,6 +45616,7 @@ var ReflectorRunner = class {
45346
45616
  this.storage.setBufferingReflectionFlag(record.id, false).catch(() => {});
45347
45617
  }
45348
45618
  const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
45619
+ await BufferingCoordinator.reconcileReflectionBufferHead(bufferKey, record.id, () => this.storage.getObservationalMemory(record.threadId, record.resourceId));
45349
45620
  if (this.buffering.isAsyncBufferingInProgress(bufferKey)) return false;
45350
45621
  if (BufferingCoordinator.lastBufferedBoundary.has(bufferKey)) return false;
45351
45622
  if (record.bufferedReflection) return false;
@@ -45374,7 +45645,7 @@ var ReflectorRunner = class {
45374
45645
  omDebug(`[OM:reflect] isReflecting=true and active in this process, skipping`);
45375
45646
  return;
45376
45647
  }
45377
- omDebug(`[OM:reflect] isReflecting=true but NOT active in this process — stale flag from dead process, clearing`);
45648
+ omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
45378
45649
  await this.storage.setReflectingFlag(record.id, false);
45379
45650
  }
45380
45651
  if (this.buffering.isAsyncReflectionEnabled()) {
@@ -45388,10 +45659,15 @@ var ReflectorRunner = class {
45388
45659
  else {
45389
45660
  const activationPoint = reflectThreshold * this.reflectionConfig.bufferActivation;
45390
45661
  if (observationTokens < activationPoint) {
45391
- omDebug(`[OM:reflect] skipping async reflection — observationTokens (${observationTokens}) below activation point (${activationPoint}), triggered by ${activationTriggeredBy}`);
45662
+ omDebug(`[OM:reflect] skipping async reflection \u2014 observationTokens (${observationTokens}) below activation point (${activationPoint}), triggered by ${activationTriggeredBy}`);
45663
+ return;
45664
+ }
45665
+ const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
45666
+ if (this.buffering.isAsyncBufferingInProgress(bufferKey) || BufferingCoordinator.lastBufferedBoundary.has(bufferKey)) {
45667
+ omDebug(`[OM:reflect] skipping async reflection \u2014 reflection buffer already active or present for ${bufferKey}`);
45392
45668
  return;
45393
45669
  }
45394
- omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) — starting background reflection`);
45670
+ omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) \u2014 starting background reflection`);
45395
45671
  this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
45396
45672
  return;
45397
45673
  }
@@ -45399,7 +45675,7 @@ var ReflectorRunner = class {
45399
45675
  if (activationTriggeredBy === "threshold") {
45400
45676
  const suppressedAtTokens = this.syncReflectionSuppression.get(lockKey);
45401
45677
  if (suppressedAtTokens !== void 0 && observationTokens === suppressedAtTokens) {
45402
- omDebug(`[OM:reflect] skipping sync reflection — observations unchanged at ${observationTokens} tokens since the last unproductive attempt; retrying once they change`);
45678
+ omDebug(`[OM:reflect] skipping sync reflection \u2014 observations unchanged at ${observationTokens} tokens since the last unproductive attempt; retrying once they change`);
45403
45679
  return;
45404
45680
  }
45405
45681
  }
@@ -46240,7 +46516,7 @@ var ObservationalMemory = class ObservationalMemory {
46240
46516
  const asyncBufferingDisabled = config.observation?.bufferTokens === false || config.scope === "resource" && !userExplicitlyConfiguredAsync;
46241
46517
  if (isSharedBudget && !asyncBufferingDisabled) {
46242
46518
  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).");
46243
- 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.");
46519
+ 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.");
46244
46520
  }
46245
46521
  const observationActivateAfterIdle = config.observation?.activateAfterIdle ?? config.activateAfterIdle;
46246
46522
  const observationActivateAfterIdlePath = config.observation?.activateAfterIdle !== void 0 ? "observation.activateAfterIdle" : "activateAfterIdle";
@@ -46337,7 +46613,7 @@ var ObservationalMemory = class ObservationalMemory {
46337
46613
  hasWarnedResourceScopeDeprecation = true;
46338
46614
  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");
46339
46615
  }
46340
- 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}`);
46616
+ 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}`);
46341
46617
  }
46342
46618
  __registerMastra(mastra) {
46343
46619
  this.mastra = mastra;
@@ -46618,7 +46894,7 @@ var ObservationalMemory = class ObservationalMemory {
46618
46894
  threadId: null,
46619
46895
  resourceId: resourceId ?? threadId
46620
46896
  };
46621
- 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.");
46897
+ 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.");
46622
46898
  return {
46623
46899
  threadId,
46624
46900
  resourceId: resourceId ?? threadId
@@ -46929,7 +47205,7 @@ var ObservationalMemory = class ObservationalMemory {
46929
47205
  const isImportant = new Array(totalCount);
46930
47206
  for (let i = 0; i < totalCount; i++) {
46931
47207
  lineTokens[i] = this.tokenCounter.countString(lines[i]);
46932
- isImportant[i] = lines[i].includes("🔴") || lines[i].includes("✅");
47208
+ isImportant[i] = lines[i].includes("\u{1F534}") || lines[i].includes("\u2705");
46933
47209
  }
46934
47210
  const suffixTokens = new Array(totalCount + 1);
46935
47211
  suffixTokens[totalCount] = 0;
@@ -47262,7 +47538,7 @@ ${formattedMessages}
47262
47538
  resourceId: freshRecord.resourceId ?? void 0
47263
47539
  });
47264
47540
  } catch (err) {
47265
- omError("[OM] Failed to persist sealed messages before buffering — skipping observation cycle", err);
47541
+ omError("[OM] Failed to persist sealed messages before buffering \u2014 skipping observation cycle", err);
47266
47542
  return;
47267
47543
  }
47268
47544
  const cycleId = `buffer-obs-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
@@ -48412,7 +48688,7 @@ ${formattedMessages}
48412
48688
  usage: void 0
48413
48689
  };
48414
48690
  }
48415
- omDebug(`[OM:reflect] isReflecting=true but NOT active in this process — stale flag from dead process, clearing`);
48691
+ omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
48416
48692
  await this.storage.setReflectingFlag(record.id, false);
48417
48693
  }
48418
48694
  await this.storage.setReflectingFlag(record.id, true);
@@ -48646,7 +48922,7 @@ ${formattedMessages}
48646
48922
  };
48647
48923
  const TEMPORAL_GAP_REMINDER_TYPE = "temporal-gap";
48648
48924
  function getTemporalGapReminderText(gapText, timestamp) {
48649
- return `${gapText} — ${formatTemporalTimestamp(new Date(timestamp))}`;
48925
+ return `${gapText} \u2014 ${formatTemporalTimestamp(new Date(timestamp))}`;
48650
48926
  }
48651
48927
  function getTemporalGapReminderMetadata(message, gapText, gapMs, timestamp) {
48652
48928
  const formattedTimestamp = formatTemporalTimestamp(new Date(timestamp));
@@ -48867,14 +49143,14 @@ var ObservationalMemoryProcessor = class {
48867
49143
  omDebug(`[OM:processInputStep:ENTER] step=${stepNumber}, hasMastraMemory=${!!requestContext?.get("MastraMemory")}, hasMemoryInfo=${!!messageList?.serialize()?.memoryInfo?.threadId}`);
48868
49144
  const context = this.engine.getThreadContext(requestContext, messageList);
48869
49145
  if (!context) {
48870
- omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null — returning early`);
49146
+ omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null \u2014 returning early`);
48871
49147
  return messageList;
48872
49148
  }
48873
49149
  const gatewayMemoryManaged = await isGatewayMemoryManaged(model);
48874
49150
  state[GATEWAY_STATE_KEY] = gatewayMemoryManaged;
48875
49151
  if (gatewayMemoryManaged) {
48876
49152
  await this.endActiveTurn(state);
48877
- omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory — skipping local processing`);
49153
+ omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory \u2014 skipping local processing`);
48878
49154
  return messageList;
48879
49155
  }
48880
49156
  const { threadId, resourceId } = context;
@@ -49095,7 +49371,7 @@ var ObservationalMemoryProcessor = class {
49095
49371
  if (!context) return;
49096
49372
  if (parseMemoryRequestContext(requestContext)?.memoryConfig?.readOnly) return;
49097
49373
  state[CONTEXT_OVERFLOW_STEP_KEY] = stepNumber;
49098
- omDebug(`[OM:processAPIError] context overflow at step ${stepNumber} — observing pending messages`);
49374
+ omDebug(`[OM:processAPIError] context overflow at step ${stepNumber} \u2014 observing pending messages`);
49099
49375
  const { threadId, resourceId } = context;
49100
49376
  await this.engine.waitForBuffering(threadId, resourceId, void 0, args.abortSignal);
49101
49377
  const messages = getObservableMessages(messageList);
@@ -51694,7 +51970,7 @@ var import_ignore = /* @__PURE__ */ __toESM$1((/* @__PURE__ */ __commonJSMin$1((
51694
51970
  const SPACE = " ";
51695
51971
  const ESCAPE = "\\";
51696
51972
  const REGEX_LITERAL_SPECIAL = /[.*+?()[\]{}^$|\\/]/;
51697
- const BOM = "";
51973
+ const BOM = "\uFEFF";
51698
51974
  const REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
51699
51975
  const REGEX_ANCHORED_GLOBSTAR = /^\/\*{2,}$/;
51700
51976
  const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
@@ -51791,8 +52067,8 @@ var import_ignore = /* @__PURE__ */ __toESM$1((/* @__PURE__ */ __commonJSMin$1((
51791
52067
  const NEVER_MATCH = "[]";
51792
52068
  const PLACEHOLDER = "\0";
51793
52069
  const REGEX_RESTORE_PLACEHOLDER = new RegExp(`${PLACEHOLDER}(\\d+)${PLACEHOLDER}`, "g");
51794
- const TRAILING_WILDCARD = "";
51795
- const TRAILING_DOUBLESTAR = "";
52070
+ const TRAILING_WILDCARD = "\uE000";
52071
+ const TRAILING_DOUBLESTAR = "\uE001";
51796
52072
  const isReserved = (char) => char === PLACEHOLDER || char === TRAILING_WILDCARD || char === TRAILING_DOUBLESTAR;
51797
52073
  const extractBrackets = (pattern) => {
51798
52074
  const sources = [];
@@ -52562,7 +52838,7 @@ async function logGitState(targetPath, label) {
52562
52838
  const gitStatusResult = await git(targetPath, "status", "--porcelain");
52563
52839
  const gitLogResult = await git(targetPath, "log", "--oneline", "-3");
52564
52840
  const gitCountResult = await git(targetPath, "rev-list", "--count", "HEAD");
52565
- console.info(`📊 Git state ${label}:`);
52841
+ console.info(`\u{1F4CA} Git state ${label}:`);
52566
52842
  console.info("Status:", gitStatusResult.stdout.trim() || "Clean working directory");
52567
52843
  console.info("Recent commits:", gitLogResult.stdout.trim());
52568
52844
  console.info("Total commits:", gitCountResult.stdout.trim());
@@ -52654,9 +52930,9 @@ async function gitCheckoutBranch(branchName, targetPath) {
52654
52930
  async function backupAndReplaceFile(sourceFile, targetFile) {
52655
52931
  const backupFile = `${targetFile}.backup-${Date.now()}`;
52656
52932
  await copyFile(targetFile, backupFile);
52657
- console.info(`📦 Created backup: ${basename(backupFile)}`);
52933
+ console.info(`\u{1F4E6} Created backup: ${basename(backupFile)}`);
52658
52934
  await copyFile(sourceFile, targetFile);
52659
- console.info(`🔄 Replaced file with template version (backup created)`);
52935
+ console.info(`\u{1F504} Replaced file with template version (backup created)`);
52660
52936
  }
52661
52937
  async function renameAndCopyFile(sourceFile, targetFile) {
52662
52938
  let counter = 1;
@@ -52670,7 +52946,7 @@ async function renameAndCopyFile(sourceFile, targetFile) {
52670
52946
  counter++;
52671
52947
  }
52672
52948
  await copyFile(sourceFile, uniqueTargetFile);
52673
- console.info(`📝 Copied with unique name: ${basename(uniqueTargetFile)}`);
52949
+ console.info(`\u{1F4DD} Copied with unique name: ${basename(uniqueTargetFile)}`);
52674
52950
  return uniqueTargetFile;
52675
52951
  }
52676
52952
  const isValidMastraLanguageModel = (model) => {
@@ -52708,7 +52984,7 @@ const mergeGitignoreFiles = (targetContent, templateContent, templateSlug) => {
52708
52984
  const isNegation = normalized.startsWith("!");
52709
52985
  const basePath = isNegation ? normalized.slice(1) : normalized;
52710
52986
  if (!(isNegation ? existingEntries.has(basePath) : existingEntries.has("!" + basePath))) newEntries.push(trimmed);
52711
- else console.info(`⚠ Skipping conflicting .gitignore rule: ${trimmed} (conflicts with existing rule)`);
52987
+ else console.info(`\u26A0 Skipping conflicting .gitignore rule: ${trimmed} (conflicts with existing rule)`);
52712
52988
  }
52713
52989
  }
52714
52990
  }
@@ -52738,7 +53014,7 @@ const mergeEnvFiles = (targetContent, templateVariables, templateSlug) => {
52738
53014
  key,
52739
53015
  value
52740
53016
  });
52741
- else console.info(`⚠ Skipping existing environment variable: ${key} (already exists in .env)`);
53017
+ else console.info(`\u26A0 Skipping existing environment variable: ${key} (already exists in .env)`);
52742
53018
  if (newVars.length === 0) return targetContent;
52743
53019
  const result = [...targetLines];
52744
53020
  const lastLine = result[result.length - 1];
@@ -52793,7 +53069,7 @@ const createModelInstance = async (provider, modelId, version = "v2") => {
52793
53069
  try {
52794
53070
  const providerFn = version === `v1` ? { v1: {
52795
53071
  openai: async () => {
52796
- const { openai } = await import("./dist-C_7xKME1.js");
53072
+ const { openai } = await import("./dist-Bz6gINFc.js");
52797
53073
  return openai(modelId);
52798
53074
  },
52799
53075
  anthropic: async () => {
@@ -52862,25 +53138,25 @@ IF NO PROJECT EXISTS, USE THE MANAGEPROJECT TOOL TO CREATE A NEW PROJECT
52862
53138
 
52863
53139
  DO NOT INCLUDE TODOS IN THE CODE, UNLESS SPECIFICALLY ASKED TO DO SO, CREATE REAL WORLD CODE
52864
53140
 
52865
- ### 1. 🔍 **UNDERSTAND** (Information Gathering)
53141
+ ### 1. \u{1F50D} **UNDERSTAND** (Information Gathering)
52866
53142
  - **Explore Mastra Docs**: Use docs tools to understand relevant Mastra patterns and APIs
52867
53143
  - **Analyze Project**: Use file exploration to understand existing codebase structure
52868
53144
  - **Web Research**: Search for packages, examples, or solutions when docs are insufficient
52869
53145
  - **Clarify Requirements**: Ask targeted questions only when critical information is missing
52870
53146
 
52871
- ### 2. 📋 **PLAN** (Strategy & Design)
53147
+ ### 2. \u{1F4CB} **PLAN** (Strategy & Design)
52872
53148
  - **Architecture**: Design using Mastra conventions (agents, tools, workflows, memory)
52873
53149
  - **Dependencies**: Identify required packages and Mastra components
52874
53150
  - **Integration**: Plan how to integrate with existing project structure
52875
53151
  - **Validation**: Define how to test and verify the implementation
52876
53152
 
52877
- ### 3. 🛠️ **BUILD** (Implementation)
53153
+ ### 3. \u{1F6E0}\uFE0F **BUILD** (Implementation)
52878
53154
  - **Install First**: Use \`manageProject\` tool to install required packages
52879
53155
  - **Follow Patterns**: Implement using established Mastra conventions
52880
53156
  - **Real Code Only**: Build actual working functionality, never mock implementations
52881
53157
  - **Environment Setup**: Create proper .env configuration and documentation
52882
53158
 
52883
- ### 4. ✅ **VALIDATE** (Quality Assurance)
53159
+ ### 4. \u2705 **VALIDATE** (Quality Assurance)
52884
53160
  - **Code Validation**: Run \`validateCode\` with types and lint checks
52885
53161
  - **Testing**: Execute tests if available
52886
53162
  - **Server Testing**: Use \`manageServer\` and \`httpRequest\` for API validation
@@ -52977,23 +53253,23 @@ DO NOT INCLUDE TODOS IN THE CODE, UNLESS SPECIFICALLY ASKED TO DO SO, CREATE REA
52977
53253
  ## Output Requirements
52978
53254
 
52979
53255
  ### Code Quality
52980
- - ✅ TypeScript compilation passes
52981
- - ✅ ESLint validation passes
52982
- - ✅ Proper error handling implemented
52983
- - ✅ Environment variables configured
52984
- - ✅ Tests included when appropriate
53256
+ - \u2705 TypeScript compilation passes
53257
+ - \u2705 ESLint validation passes
53258
+ - \u2705 Proper error handling implemented
53259
+ - \u2705 Environment variables configured
53260
+ - \u2705 Tests included when appropriate
52985
53261
 
52986
53262
  ### Documentation
52987
- - ✅ Clear setup instructions
52988
- - ✅ Environment variable documentation
52989
- - ✅ Usage examples provided
52990
- - ✅ API documentation for custom tools
53263
+ - \u2705 Clear setup instructions
53264
+ - \u2705 Environment variable documentation
53265
+ - \u2705 Usage examples provided
53266
+ - \u2705 API documentation for custom tools
52991
53267
 
52992
53268
  ### Integration
52993
- - ✅ Follows Mastra conventions
52994
- - ✅ Integrates with existing project
52995
- - ✅ Proper imports and exports
52996
- - ✅ Compatible with Mastra ecosystem
53269
+ - \u2705 Follows Mastra conventions
53270
+ - \u2705 Integrates with existing project
53271
+ - \u2705 Proper imports and exports
53272
+ - \u2705 Compatible with Mastra ecosystem
52997
53273
 
52998
53274
  ## Project Context
52999
53275
 
@@ -53540,7 +53816,7 @@ export const mastra = new Mastra({
53540
53816
  }),
53541
53817
  validateCode: createTool({
53542
53818
  id: "validate-code",
53543
- description: "Validates code using a fast hybrid approach: syntax → semantic → lint. RECOMMENDED: Always provide specific files for optimal performance and accuracy.",
53819
+ description: "Validates code using a fast hybrid approach: syntax \u2192 semantic \u2192 lint. RECOMMENDED: Always provide specific files for optimal performance and accuracy.",
53544
53820
  inputSchema: z$2.object({
53545
53821
  projectPath: z$2.string().optional().describe("Path to the project to validate (defaults to current project)"),
53546
53822
  validationType: z$2.array(z$2.enum([
@@ -53550,7 +53826,7 @@ export const mastra = new Mastra({
53550
53826
  "tests",
53551
53827
  "build"
53552
53828
  ])).describe("Types of validation to perform. Recommended: [\"types\", \"lint\"] for code quality"),
53553
- files: z$2.array(z$2.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.")
53829
+ files: z$2.array(z$2.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.")
53554
53830
  }),
53555
53831
  outputSchema: z$2.object({
53556
53832
  valid: z$2.boolean(),
@@ -55433,8 +55709,8 @@ For each Mastra project directory you analyze:
55433
55709
  IMPORTANT - Naming Consistency Rules:
55434
55710
  - For ALL unit types (including 'other'), the 'name' field should be the filename WITHOUT extension
55435
55711
  - For structured units (agents, workflows, tools, etc.), prefer the actual export name if clearly identifiable
55436
- - use the base filename without extension for the id (e.g., 'util.ts' → name: 'util')
55437
- - use the relative path from the template root for the file (e.g., 'src/mastra/lib/util.ts' → file: 'src/mastra/lib/util.ts')
55712
+ - use the base filename without extension for the id (e.g., 'util.ts' \u2192 name: 'util')
55713
+ - 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')
55438
55714
 
55439
55715
  Return the actual exported names of the units, as well as the file names.`,
55440
55716
  name: "Mastra Project Discoverer",
@@ -55790,7 +56066,7 @@ const programmaticFileCopyStep = createStep({
55790
56066
  sourceFile: unit.file,
55791
56067
  targetFile: `${targetDir}/${convertedFileName}`
55792
56068
  });
55793
- console.info(`⏭️ Skipped ${unit.kind} "${unit.id}": file already exists`);
56069
+ console.info(`\u23ED\uFE0F Skipped ${unit.kind} "${unit.id}": file already exists`);
55794
56070
  continue;
55795
56071
  case "backup-and-replace": try {
55796
56072
  await backupAndReplaceFile(sourceFile, targetFile);
@@ -55802,7 +56078,7 @@ const programmaticFileCopyStep = createStep({
55802
56078
  id: unit.id
55803
56079
  }
55804
56080
  });
55805
- console.info(`🔄 Replaced ${unit.kind} "${unit.id}": ${unit.file} → ${convertedFileName} (backup created)`);
56081
+ console.info(`\u{1F504} Replaced ${unit.kind} "${unit.id}": ${unit.file} \u2192 ${convertedFileName} (backup created)`);
55806
56082
  continue;
55807
56083
  } catch (backupError) {
55808
56084
  conflicts.push({
@@ -55826,7 +56102,7 @@ const programmaticFileCopyStep = createStep({
55826
56102
  id: unit.id
55827
56103
  }
55828
56104
  });
55829
- console.info(`📝 Renamed ${unit.kind} "${unit.id}": ${unit.file} → ${basename(uniqueTargetFile)}`);
56105
+ console.info(`\u{1F4DD} Renamed ${unit.kind} "${unit.id}": ${unit.file} \u2192 ${basename(uniqueTargetFile)}`);
55830
56106
  continue;
55831
56107
  } catch (renameError) {
55832
56108
  conflicts.push({
@@ -55864,7 +56140,7 @@ const programmaticFileCopyStep = createStep({
55864
56140
  id: unit.id
55865
56141
  }
55866
56142
  });
55867
- console.info(`✓ Copied ${unit.kind} "${unit.id}": ${unit.file} → ${convertedFileName}`);
56143
+ console.info(`\u2713 Copied ${unit.kind} "${unit.id}": ${unit.file} \u2192 ${convertedFileName}`);
55868
56144
  } catch (copyError) {
55869
56145
  conflicts.push({
55870
56146
  unit: {
@@ -55891,7 +56167,7 @@ const programmaticFileCopyStep = createStep({
55891
56167
  id: "tsconfig.json"
55892
56168
  }
55893
56169
  });
55894
- console.info("✓ Copied tsconfig.json from template to target");
56170
+ console.info("\u2713 Copied tsconfig.json from template to target");
55895
56171
  } else {
55896
56172
  await writeFile(targetTsconfig, JSON.stringify({
55897
56173
  compilerOptions: {
@@ -55927,7 +56203,7 @@ const programmaticFileCopyStep = createStep({
55927
56203
  id: "tsconfig.json"
55928
56204
  }
55929
56205
  });
55930
- console.info("✓ Generated minimal tsconfig.json in target");
56206
+ console.info("\u2713 Generated minimal tsconfig.json in target");
55931
56207
  }
55932
56208
  }
55933
56209
  } catch (e) {
@@ -55956,7 +56232,7 @@ const programmaticFileCopyStep = createStep({
55956
56232
  id: "mastra-index"
55957
56233
  }
55958
56234
  });
55959
- console.info("✓ Copied Mastra index file from template");
56235
+ console.info("\u2713 Copied Mastra index file from template");
55960
56236
  }
55961
56237
  }
55962
56238
  } catch (e) {
@@ -55985,7 +56261,7 @@ const programmaticFileCopyStep = createStep({
55985
56261
  id: "gitignore"
55986
56262
  }
55987
56263
  });
55988
- console.info("✓ Copied .gitignore from template to target");
56264
+ console.info("\u2713 Copied .gitignore from template to target");
55989
56265
  } else {
55990
56266
  const targetContent = await readFile(targetGitignore, "utf-8");
55991
56267
  const templateContent = await readFile(templateGitignore, "utf-8");
@@ -56001,8 +56277,8 @@ const programmaticFileCopyStep = createStep({
56001
56277
  id: "gitignore-merge"
56002
56278
  }
56003
56279
  });
56004
- console.info(`✓ Merged template .gitignore entries into existing .gitignore (${addedLines} new entries)`);
56005
- } else console.info("ℹ No new .gitignore entries to add from template");
56280
+ console.info(`\u2713 Merged template .gitignore entries into existing .gitignore (${addedLines} new entries)`);
56281
+ } else console.info("\u2139 No new .gitignore entries to add from template");
56006
56282
  }
56007
56283
  }
56008
56284
  } catch (e) {
@@ -56031,7 +56307,7 @@ const programmaticFileCopyStep = createStep({
56031
56307
  id: "env"
56032
56308
  }
56033
56309
  });
56034
- console.info(`✓ Created .env file with ${Object.keys(variables).length} template variables`);
56310
+ console.info(`\u2713 Created .env file with ${Object.keys(variables).length} template variables`);
56035
56311
  } else {
56036
56312
  const targetContent = await readFile(targetEnv, "utf-8");
56037
56313
  const mergedContent = mergeEnvFiles(targetContent, variables, slug);
@@ -56046,8 +56322,8 @@ const programmaticFileCopyStep = createStep({
56046
56322
  id: "env-merge"
56047
56323
  }
56048
56324
  });
56049
- console.info(`✓ Merged new environment variables into existing .env file (${addedLines} new entries)`);
56050
- } else console.info("ℹ No new environment variables to add (all already exist in .env)");
56325
+ console.info(`\u2713 Merged new environment variables into existing .env file (${addedLines} new entries)`);
56326
+ } else console.info("\u2139 No new environment variables to add (all already exist in .env)");
56051
56327
  }
56052
56328
  }
56053
56329
  } catch (e) {
@@ -56064,7 +56340,7 @@ const programmaticFileCopyStep = createStep({
56064
56340
  if (copiedFiles.length > 0) try {
56065
56341
  const fileList = copiedFiles.map((f) => f.destination);
56066
56342
  await gitAddAndCommit(targetPath, `feat(template): copy ${copiedFiles.length} files from ${slug}@${commitSha.substring(0, 7)}`, fileList, { skipIfNoStaged: true });
56067
- console.info(`✓ Committed ${copiedFiles.length} copied files`);
56343
+ console.info(`\u2713 Committed ${copiedFiles.length} copied files`);
56068
56344
  } catch (commitError) {
56069
56345
  console.warn("Failed to commit copied files:", commitError);
56070
56346
  }
@@ -56308,7 +56584,7 @@ Start by listing your tasks and work through them systematically!
56308
56584
  content: toolResult.content || "",
56309
56585
  notes: toolResult.notes
56310
56586
  });
56311
- console.info(`📋 Task completed: ${toolResult.taskId} - ${toolResult.content}`);
56587
+ console.info(`\u{1F4CB} Task completed: ${toolResult.taskId} - ${toolResult.content}`);
56312
56588
  }
56313
56589
  } catch (parseError) {
56314
56590
  console.warn("Failed to parse task management result:", parseError);
@@ -56360,7 +56636,7 @@ const validationAndFixStep = createStep({
56360
56636
  const { commitSha, slug, orderedUnits, templateDir, copiedFiles, conflictsResolved, maxIterations = 5 } = inputData;
56361
56637
  const targetPath = resolveTargetPath(inputData, requestContext);
56362
56638
  if (!(copiedFiles.length > 0 || conflictsResolved && conflictsResolved.length > 0)) {
56363
- console.info("⏭️ Skipping validation - no files copied or conflicts resolved");
56639
+ console.info("\u23ED\uFE0F Skipping validation - no files copied or conflicts resolved");
56364
56640
  return {
56365
56641
  success: true,
56366
56642
  applied: false,
@@ -56372,7 +56648,7 @@ const validationAndFixStep = createStep({
56372
56648
  }
56373
56649
  };
56374
56650
  }
56375
- console.info(`📋 Changes detected: ${copiedFiles.length} files copied, ${conflictsResolved?.length || 0} conflicts resolved`);
56651
+ console.info(`\u{1F4CB} Changes detected: ${copiedFiles.length} files copied, ${conflictsResolved?.length || 0} conflicts resolved`);
56376
56652
  let currentIteration = 1;
56377
56653
  try {
56378
56654
  const model = await resolveModel({
@@ -56464,7 +56740,7 @@ CRITICAL TOOL SELECTION GUIDE:
56464
56740
  - **writeFile**: ONLY for creating new files that don't exist
56465
56741
  Example: creating missing index.ts barrel files
56466
56742
 
56467
- CRITICAL WRITEFILЕ SAFETY RULES:
56743
+ CRITICAL WRITEFIL\u0415 SAFETY RULES:
56468
56744
  - ONLY use writeFile for creating NEW files that don't exist
56469
56745
  - ALWAYS check with readFile first to verify file doesn't exist
56470
56746
  - NEVER use writeFile to overwrite existing files - use multiEdit or replaceLines instead
@@ -56549,10 +56825,10 @@ Previous iterations may have fixed some issues, so start by re-running validateC
56549
56825
  if (iterationErrors > 0 && lastValidationResult?.errors) validationResults.lastValidationErrors = lastValidationResult.errors;
56550
56826
  console.info(`Iteration ${currentIteration} complete: ${iterationErrors} errors remaining`);
56551
56827
  if (iterationErrors === 0) {
56552
- console.info(`✅ All validation issues resolved in ${currentIteration} iterations!`);
56828
+ console.info(`\u2705 All validation issues resolved in ${currentIteration} iterations!`);
56553
56829
  break;
56554
56830
  } else if (currentIteration >= maxIterations) {
56555
- console.info(`⚠️ Max iterations (${maxIterations}) reached. ${iterationErrors} errors still remaining.`);
56831
+ console.info(`\u26A0\uFE0F Max iterations (${maxIterations}) reached. ${iterationErrors} errors still remaining.`);
56556
56832
  break;
56557
56833
  }
56558
56834
  currentIteration++;
@@ -56592,7 +56868,7 @@ Previous iterations may have fixed some issues, so start by re-running validateC
56592
56868
  recursive: true,
56593
56869
  force: true
56594
56870
  });
56595
- console.info(`✓ Cleaned up template directory: ${templateDir}`);
56871
+ console.info(`\u2713 Cleaned up template directory: ${templateDir}`);
56596
56872
  } catch (cleanupError) {
56597
56873
  console.warn("Failed to cleanup template directory:", cleanupError);
56598
56874
  }
@@ -59686,11 +59962,11 @@ function createPlanningAndApprovalWorkflow() {
59686
59962
  }
59687
59963
  createPlanningAndApprovalWorkflow();
59688
59964
  const workflowResearch = `
59689
- ## 🔍 **COMPREHENSIVE MASTRA WORKFLOW RESEARCH SUMMARY**
59965
+ ## \u{1F50D} **COMPREHENSIVE MASTRA WORKFLOW RESEARCH SUMMARY**
59690
59966
 
59691
59967
  Based on extensive research of Mastra documentation and examples, here's essential information for building effective Mastra workflows:
59692
59968
 
59693
- ### **📋 WORKFLOW FUNDAMENTALS**
59969
+ ### **\u{1F4CB} WORKFLOW FUNDAMENTALS**
59694
59970
 
59695
59971
  **Core Components:**
59696
59972
  - **\`createWorkflow()\`**: Main factory function that creates workflow instances
@@ -59714,7 +59990,7 @@ const workflow = createWorkflow({
59714
59990
  .commit(); // CRITICAL: Makes workflow executable
59715
59991
  \`\`\`
59716
59992
 
59717
- ### **🔧 STEP CREATION PATTERNS**
59993
+ ### **\u{1F527} STEP CREATION PATTERNS**
59718
59994
 
59719
59995
  **Standard Step Definition:**
59720
59996
  \`\`\`typescript
@@ -59738,7 +60014,7 @@ const myStep = createStep({
59738
60014
  - \`requestContext\`: Runtime dependency injection context
59739
60015
  - \`runCount\`: Number of times this step has run (useful for retries)
59740
60016
 
59741
- ### **🔄 CONTROL FLOW METHODS**
60017
+ ### **\u{1F504} CONTROL FLOW METHODS**
59742
60018
 
59743
60019
  **Sequential Execution:**
59744
60020
  - \`.then(step)\`: Execute steps one after another
@@ -59760,7 +60036,7 @@ const myStep = createStep({
59760
60036
  **Data Transformation:**
59761
60037
  - \`.map(({ inputData, getStepResult, getInitData }) => transformedData)\`: Transform data between steps
59762
60038
 
59763
- ### **⏸️ SUSPEND & RESUME CAPABILITIES**
60039
+ ### **\u23F8\uFE0F SUSPEND & RESUME CAPABILITIES**
59764
60040
 
59765
60041
  **For Human-in-the-Loop Workflows:**
59766
60042
  \`\`\`typescript
@@ -59791,7 +60067,7 @@ if (result.status === "suspended") {
59791
60067
  }
59792
60068
  \`\`\`
59793
60069
 
59794
- ### **🛠️ INTEGRATING AGENTS & TOOLS**
60070
+ ### **\u{1F6E0}\uFE0F INTEGRATING AGENTS & TOOLS**
59795
60071
 
59796
60072
  **Using Agents in Steps:**
59797
60073
  \`\`\`typescript
@@ -59824,24 +60100,24 @@ const step = createStep({
59824
60100
  });
59825
60101
  \`\`\`
59826
60102
 
59827
- ### **🗂️ PROJECT ORGANIZATION PATTERNS**
60103
+ ### **\u{1F5C2}\uFE0F PROJECT ORGANIZATION PATTERNS**
59828
60104
 
59829
60105
  **MANDATORY Workflow Organization:**
59830
60106
  Each workflow MUST be organized in its own dedicated folder with separated concerns:
59831
60107
 
59832
60108
  \`\`\`
59833
60109
  src/mastra/workflows/
59834
- ├── my-workflow-name/ # Kebab-case folder name
59835
- │ ├── types.ts # All Zod schemas and TypeScript types
59836
- │ ├── steps.ts # All individual step definitions
59837
- │ ├── workflow.ts # Main workflow composition and export
59838
- │ └── utils.ts # Helper functions (if needed)
59839
- ├── another-workflow/
59840
- │ ├── types.ts
59841
- │ ├── steps.ts
59842
- │ ├── workflow.ts
59843
- │ └── utils.ts
59844
- └── index.ts # Export all workflows
60110
+ \u251C\u2500\u2500 my-workflow-name/ # Kebab-case folder name
60111
+ \u2502 \u251C\u2500\u2500 types.ts # All Zod schemas and TypeScript types
60112
+ \u2502 \u251C\u2500\u2500 steps.ts # All individual step definitions
60113
+ \u2502 \u251C\u2500\u2500 workflow.ts # Main workflow composition and export
60114
+ \u2502 \u2514\u2500\u2500 utils.ts # Helper functions (if needed)
60115
+ \u251C\u2500\u2500 another-workflow/
60116
+ \u2502 \u251C\u2500\u2500 types.ts
60117
+ \u2502 \u251C\u2500\u2500 steps.ts
60118
+ \u2502 \u251C\u2500\u2500 workflow.ts
60119
+ \u2502 \u2514\u2500\u2500 utils.ts
60120
+ \u2514\u2500\u2500 index.ts # Export all workflows
59845
60121
  \`\`\`
59846
60122
 
59847
60123
  **CRITICAL File Organization Rules:**
@@ -59865,7 +60141,7 @@ export const mastra = new Mastra({
59865
60141
  });
59866
60142
  \`\`\`
59867
60143
 
59868
- ### **📦 ESSENTIAL DEPENDENCIES**
60144
+ ### **\u{1F4E6} ESSENTIAL DEPENDENCIES**
59869
60145
 
59870
60146
  **Required Packages:**
59871
60147
  \`\`\`json
@@ -59882,7 +60158,7 @@ export const mastra = new Mastra({
59882
60158
  - \`@ai-sdk/openai\`: For AI model integration
59883
60159
  - \`ai\`: For AI SDK functionality
59884
60160
 
59885
- ### **✅ WORKFLOW BEST PRACTICES**
60161
+ ### **\u2705 WORKFLOW BEST PRACTICES**
59886
60162
 
59887
60163
  **Schema Design:**
59888
60164
  - Use descriptive property names in schemas
@@ -59904,7 +60180,7 @@ export const mastra = new Mastra({
59904
60180
  - Access previous step results with \`getStepResult(stepInstance)\`
59905
60181
  - Use \`getInitData()\` to access original workflow input
59906
60182
 
59907
- ### **🚀 EXECUTION PATTERNS**
60183
+ ### **\u{1F680} EXECUTION PATTERNS**
59908
60184
 
59909
60185
  **Running Workflows:**
59910
60186
  \`\`\`typescript
@@ -59927,7 +60203,7 @@ run.watch((event) => console.log(event));
59927
60203
  - \`"suspended"\`: Paused awaiting input
59928
60204
  - \`"failed"\`: Encountered error
59929
60205
 
59930
- ### **🔗 ADVANCED FEATURES**
60206
+ ### **\u{1F517} ADVANCED FEATURES**
59931
60207
 
59932
60208
  **Nested Workflows:**
59933
60209
  - Use workflows as steps: \`.then(otherWorkflow)\`
@@ -59990,11 +60266,11 @@ CRITICAL WORKFLOW EXECUTION REQUIREMENTS:
59990
60266
  MANDATORY WORKFLOW FOLDER STRUCTURE:
59991
60267
  When ${context.action === "create" ? "creating a new workflow" : "editing a workflow"}, you MUST organize files as follows:
59992
60268
 
59993
- 📁 src/mastra/workflows/${context.workflowName?.toLowerCase().replace(/[^a-z0-9]/g, "-") || "new-workflow"}/
59994
- ├── 📄 types.ts # All Zod schemas and TypeScript types
59995
- ├── 📄 steps.ts # All individual step definitions
59996
- ├── 📄 workflow.ts # Main workflow composition and export
59997
- └── 📄 utils.ts # Helper functions (if needed)
60269
+ \u{1F4C1} src/mastra/workflows/${context.workflowName?.toLowerCase().replace(/[^a-z0-9]/g, "-") || "new-workflow"}/
60270
+ \u251C\u2500\u2500 \u{1F4C4} types.ts # All Zod schemas and TypeScript types
60271
+ \u251C\u2500\u2500 \u{1F4C4} steps.ts # All individual step definitions
60272
+ \u251C\u2500\u2500 \u{1F4C4} workflow.ts # Main workflow composition and export
60273
+ \u2514\u2500\u2500 \u{1F4C4} utils.ts # Helper functions (if needed)
59998
60274
 
59999
60275
  CRITICAL FILE ORGANIZATION RULES:
60000
60276
  - **ALWAYS create a dedicated folder** for the workflow in src/mastra/workflows/
@@ -60066,7 +60342,7 @@ ${context.resumeData ? `USER PROVIDED ANSWERS: ${JSON.stringify(context.resumeDa
60066
60342
  },
60067
60343
  validation: { instructions: `CRITICAL VALIDATION INSTRUCTIONS:
60068
60344
  - When using the validateCode tool, ALWAYS pass the specific files you created or modified using the 'files' parameter
60069
- - The tool uses a hybrid validation approach: fast syntax checking → semantic type checking → ESLint
60345
+ - The tool uses a hybrid validation approach: fast syntax checking \u2192 semantic type checking \u2192 ESLint
60070
60346
  - This is much faster than full project compilation and only shows errors from your specific files
60071
60347
  - Example: validateCode({ validationType: ['types', 'lint'], files: ['src/workflows/my-workflow.ts', 'src/agents/my-agent.ts'] })
60072
60348
  - ALWAYS validate after creating or modifying files to ensure they compile correctly` }