@mastra/server 1.86.0-alpha.7 → 1.86.0-alpha.9

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 (137) hide show
  1. package/dist/{a2a-WPGF38fX.js → a2a-CY7rgzPe.js} +1 -1
  2. package/dist/{a2a-vSZkdSRE.cjs → a2a-DwjvHqcb.cjs} +1 -1
  3. package/dist/{agent-builder-C4AIqOxt.js → agent-builder-DHnNRROR.js} +2 -2
  4. package/dist/{agent-builder-dZlRNj1k.cjs → agent-builder-anRH1X35.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-272TP94y.js → agents-CAXsXenf.js} +32 -3
  10. package/dist/{agents-mjQZV5tv.cjs → agents-GHhuyz5x.cjs} +32 -3
  11. package/dist/{api-schema-manifest-BjhiTdNv.js → api-schema-manifest-4PK1dBWt.js} +1 -1
  12. package/dist/{api-schema-manifest-DVkepK_s.cjs → api-schema-manifest-CX16hC7V.cjs} +1 -1
  13. package/dist/{auth-CM5AgF9l.cjs → auth-BR7vRIrY.cjs} +5 -3
  14. package/dist/{auth-CjT_a76k.js → auth-ChZ3dUvo.js} +5 -3
  15. package/dist/{catalogue-DH64Duv-.js → catalogue-BOzHZ1xt.js} +11 -11
  16. package/dist/{catalogue-BTE9b_mr.cjs → catalogue-DNy7Fog6.cjs} +11 -11
  17. package/dist/{conversations-CXyaNjLR.js → conversations-BjD8wOc3.js} +1 -1
  18. package/dist/{conversations-BWA_---j.cjs → conversations-CgogBOHO.cjs} +1 -1
  19. package/dist/{datasets-C1XJLHN8.js → datasets-CYdtUF8e.js} +4 -1
  20. package/dist/{datasets-hqDd4IUN.cjs → datasets-CZRqni0N.cjs} +4 -1
  21. package/dist/dist-BWVxgpEw.js +1 -0
  22. package/dist/{dist-DGwsCtT4.cjs → dist-Brw_H26B.cjs} +521 -286
  23. package/dist/{dist-CSffo32A.cjs → dist-C5_WGwU1.cjs} +1 -1
  24. package/dist/{dist-Bp1bObAq.js → dist-NBGkHBIE.js} +521 -286
  25. package/dist/docs/SKILL.md +1 -1
  26. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  27. package/dist/docs/references/docs-knowledge-overview.md +1 -1
  28. package/dist/docs/references/reference-observability-tracing-advanced-queries.md +20 -0
  29. package/dist/{dynamic-workflows-DPgV6qtS.cjs → dynamic-workflows-CEKdGcSr.cjs} +4 -4
  30. package/dist/{dynamic-workflows-DmkCJ4Lp.js → dynamic-workflows-DF9X_oDG.js} +4 -4
  31. package/dist/{editor-builder-BayzCprJ.js → editor-builder-BRzXnsRW.js} +1 -1
  32. package/dist/{editor-builder-BS2xogE_.cjs → editor-builder-G1ub9j0s.cjs} +1 -1
  33. package/dist/{knowledge-DL03nbSW.cjs → knowledge-B3768ERP.cjs} +1 -0
  34. package/dist/{knowledge-DAqUHFK5.js → knowledge-wqC0nrmu.js} +1 -0
  35. package/dist/{observability-zr7LDCQG.js → observability-URaJnI_U.js} +1 -1
  36. package/dist/{observability-Cn4P60P4.cjs → observability-zNA_CVaz.cjs} +1 -1
  37. package/dist/{plans-xGwuiZUd.js → plans-DGC1grMp.js} +1 -1
  38. package/dist/{plans-Bes_LVgv.cjs → plans-kA8E3Auv.cjs} +1 -1
  39. package/dist/probe-image-size-ntJyQKKB.cjs +13304 -0
  40. package/dist/probe-image-size-zXQBlFaQ.js +13297 -0
  41. package/dist/{responses-CwQO5y2X.js → responses--nGf7l3O.js} +1 -1
  42. package/dist/{responses-BH567IZf.cjs → responses-B4GDz-Nm.cjs} +1 -1
  43. package/dist/{routes-CrBCJmjc.js → routes-BZVlqLly.js} +17 -17
  44. package/dist/{routes-6p-xrUIq.cjs → routes-vuZLexcc.cjs} +17 -17
  45. package/dist/{schedules-0ceTSdBB.cjs → schedules-CwL28Eca.cjs} +4 -4
  46. package/dist/{schedules-D_VfFdAH.js → schedules-RWgPeypN.js} +4 -4
  47. package/dist/{scorer-versions-Bhdvt-cX.cjs → scorer-versions-DK-PGj7-.cjs} +1 -1
  48. package/dist/{scorer-versions-DhT7Lj33.js → scorer-versions-oJoK2Exw.js} +1 -1
  49. package/dist/{scores-ksmJiJnJ.js → scores-Biv7XGW_.js} +1 -1
  50. package/dist/{scores-CXNkN7Bn.cjs → scores-D0Qq7TfU.cjs} +1 -1
  51. package/dist/server/handlers/a2a.cjs +1 -1
  52. package/dist/server/handlers/a2a.js +1 -1
  53. package/dist/server/handlers/agent-builder.cjs +1 -1
  54. package/dist/server/handlers/agent-builder.js +1 -1
  55. package/dist/server/handlers/agent-controller.cjs +1 -1
  56. package/dist/server/handlers/agent-controller.js +1 -1
  57. package/dist/server/handlers/agent-versions.cjs +1 -1
  58. package/dist/server/handlers/agent-versions.js +1 -1
  59. package/dist/server/handlers/agents.cjs +1 -1
  60. package/dist/server/handlers/agents.js +1 -1
  61. package/dist/server/handlers/auth.cjs +7 -3
  62. package/dist/server/handlers/auth.d.ts +12 -4
  63. package/dist/server/handlers/auth.js +7 -3
  64. package/dist/server/handlers/conversations.cjs +1 -1
  65. package/dist/server/handlers/conversations.js +1 -1
  66. package/dist/server/handlers/datasets.cjs +16 -11
  67. package/dist/server/handlers/datasets.d.ts +6 -0
  68. package/dist/server/handlers/datasets.js +16 -11
  69. package/dist/server/handlers/dynamic-workflows.cjs +1 -1
  70. package/dist/server/handlers/dynamic-workflows.js +1 -1
  71. package/dist/server/handlers/editor-builder.cjs +1 -1
  72. package/dist/server/handlers/editor-builder.js +1 -1
  73. package/dist/server/handlers/error.cjs +1 -1
  74. package/dist/server/handlers/error.js +1 -1
  75. package/dist/server/handlers/favorites-enrichment.cjs +1 -1
  76. package/dist/server/handlers/favorites-enrichment.js +1 -1
  77. package/dist/server/handlers/knowledge.cjs +1 -1
  78. package/dist/server/handlers/knowledge.js +1 -1
  79. package/dist/server/handlers/observability.cjs +1 -1
  80. package/dist/server/handlers/observability.js +1 -1
  81. package/dist/server/handlers/plans.cjs +1 -1
  82. package/dist/server/handlers/plans.js +1 -1
  83. package/dist/server/handlers/responses.cjs +1 -1
  84. package/dist/server/handlers/responses.js +1 -1
  85. package/dist/server/handlers/schedules.cjs +1 -1
  86. package/dist/server/handlers/schedules.js +1 -1
  87. package/dist/server/handlers/scorer-versions.cjs +1 -1
  88. package/dist/server/handlers/scorer-versions.js +1 -1
  89. package/dist/server/handlers/scores.cjs +1 -1
  90. package/dist/server/handlers/scores.js +1 -1
  91. package/dist/server/handlers/stored-agent-favorites.cjs +3 -3
  92. package/dist/server/handlers/stored-agent-favorites.js +3 -3
  93. package/dist/server/handlers/stored-agents.cjs +2 -2
  94. package/dist/server/handlers/stored-agents.js +2 -2
  95. package/dist/server/handlers/stored-scorers.cjs +1 -1
  96. package/dist/server/handlers/stored-scorers.js +1 -1
  97. package/dist/server/handlers/stored-skill-favorites.cjs +2 -2
  98. package/dist/server/handlers/stored-skill-favorites.js +2 -2
  99. package/dist/server/handlers/stored-skills.cjs +1 -1
  100. package/dist/server/handlers/stored-skills.js +1 -1
  101. package/dist/server/handlers/system.cjs +1 -1
  102. package/dist/server/handlers/system.js +1 -1
  103. package/dist/server/handlers/tool-providers.cjs +2 -2
  104. package/dist/server/handlers/tool-providers.js +2 -2
  105. package/dist/server/handlers/tools.cjs +1 -1
  106. package/dist/server/handlers/tools.js +1 -1
  107. package/dist/server/handlers/voice.cjs +1 -1
  108. package/dist/server/handlers/voice.js +1 -1
  109. package/dist/server/handlers/workflows.cjs +1 -1
  110. package/dist/server/handlers/workflows.js +1 -1
  111. package/dist/server/handlers.cjs +12 -12
  112. package/dist/server/handlers.js +12 -12
  113. package/dist/server/schemas/auth.d.ts +3 -1
  114. package/dist/server/schemas/datasets.d.ts +3 -0
  115. package/dist/server/schemas/index.cjs +7 -7
  116. package/dist/server/schemas/index.js +7 -7
  117. package/dist/server/server-adapter/index.cjs +3 -3
  118. package/dist/server/server-adapter/index.js +3 -3
  119. package/dist/server/server-adapter/routes/datasets.d.ts +6 -0
  120. package/dist/{server-adapter-Ceag3til.cjs → server-adapter-CurME3ch.cjs} +4 -4
  121. package/dist/{server-adapter-BGOi-s7x.js → server-adapter-h8YRQXAC.js} +4 -4
  122. package/dist/{stored-agents-m0Knvv29.cjs → stored-agents-BS4_LGSs.cjs} +32 -32
  123. package/dist/{stored-agents-DmN_pIIl.js → stored-agents-DcyDMKP2.js} +32 -32
  124. package/dist/{stored-scorers-2F2k6XSx.js → stored-scorers-Bdz_5k57.js} +1 -1
  125. package/dist/{stored-scorers-iM2Qq9Nh.cjs → stored-scorers-D8YYszOj.cjs} +1 -1
  126. package/dist/{tool-providers-Cq3vFqgE.js → tool-providers-BN2Ni06Z.js} +2 -2
  127. package/dist/{tool-providers-BVwRJTtB.cjs → tool-providers-BeiSkVHu.cjs} +2 -2
  128. package/dist/{tools-DLZ7go-n.cjs → tools-By0RVh_O.cjs} +1 -1
  129. package/dist/{tools-CY44YtDW.js → tools-C3KBdlil.js} +1 -1
  130. package/dist/{voice-NaerSeVQ.cjs → voice-CESew8Fc.cjs} +1 -1
  131. package/dist/{voice-DTjrAgqg.js → voice-PfxY_vQg.js} +1 -1
  132. package/dist/{workflows-gIKukZ1O.cjs → workflows-CHKSHV4f.cjs} +33 -0
  133. package/dist/{workflows-D3QrUMfm.js → workflows-D5bfbang.js} +33 -0
  134. package/package.json +3 -3
  135. package/dist/dist-Bn0zFASI.js +0 -1
  136. package/dist/probe-image-size-BR5MlnnJ.cjs +0 -13304
  137. package/dist/probe-image-size-DBCcUUw_.js +0 -13297
@@ -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-CDv__4kY.js
8658
+ // ../memory/dist/src-C6oJP8WI.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,
@@ -33628,6 +33639,17 @@ function isTransientLLMError(error) {
33628
33639
  return visit(error);
33629
33640
  }
33630
33641
  /**
33642
+ * Returns true when the error says the provider account has no credits or quota left, as core's
33643
+ * provider-error classifier decides it. These can carry a retryable status (OpenAI's are HTTP 429,
33644
+ * the status of a rate limit), so `withRetry` stops on them even though `isTransientLLMError`
33645
+ * matches: the account stays unusable until someone adds credits. Rate limits are still retried.
33646
+ *
33647
+ * @internal
33648
+ */
33649
+ function isExhaustedAccountError(error) {
33650
+ return classifyProviderError(error) === "quota";
33651
+ }
33652
+ /**
33631
33653
  * Compute the backoff delay (ms) for the Nth retry (0-indexed).
33632
33654
  *
33633
33655
  * Exponential growth (`initialDelayMs * backoffFactor^attempt`) capped at
@@ -33711,7 +33733,8 @@ async function attemptWithIdleTimeout(fn, label, idleTimeoutMs, abortSignal) {
33711
33733
  /**
33712
33734
  * Run `fn` with retries on transient transport-class errors.
33713
33735
  *
33714
- * Non-transient errors (auth, validation, schema, etc.) are rethrown
33736
+ * Non-transient errors (auth, validation, schema, etc.) and errors from an
33737
+ * account with no credits or quota left (see `isExhaustedAccountError`) are rethrown
33715
33738
  * immediately. User-initiated aborts are rethrown without delay.
33716
33739
  *
33717
33740
  * @internal
@@ -33727,7 +33750,7 @@ async function withRetry(fn, opts) {
33727
33750
  } catch (error) {
33728
33751
  if (abortSignal?.aborted) throw error;
33729
33752
  if (!(error instanceof OmModelCallTimeoutError) && hasAbortInChain(error)) throw error;
33730
- if (attempt >= maxRetries || !isTransientLLMError(error)) {
33753
+ if (attempt >= maxRetries || !isTransientLLMError(error) || isExhaustedAccountError(error)) {
33731
33754
  if (attempt > 0) omDebug(`[OM:retry:${label}] giving up after ${attempt} retry/retries: ${error instanceof Error ? error.message : String(error)}`);
33732
33755
  throw error;
33733
33756
  }
@@ -34088,7 +34111,7 @@ const YEAR = String.raw`(?:19|20|21)\d{2}(?!\d)`;
34088
34111
  const MERIDIEM = String.raw`(?:[AaPp]\.[Mm]\.|[AaPp][Mm]\b)`;
34089
34112
  const TIME = String.raw`(?:,?\s+(?:at\s+)?\d{1,2}:\d{2}(?:\s*${MERIDIEM})?|\s+at\s+\d{1,2}\s*${MERIDIEM})`;
34090
34113
  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+)`;
34114
+ const RANGE_SEP = String.raw`(?:\s*[\u2013\u2014]\s*|\s*-\s*|\s+(?:to|through|until)\s+)`;
34092
34115
  /**
34093
34116
  * Dates written into observation text that carry their own year, longest forms first:
34094
34117
  * "Mar 1 - Mar 18, 2025", "May 27-28, 2023", "January 10, 2024 at 3:00 PM",
@@ -34389,15 +34412,15 @@ const SHORT_TOKEN_THRESHOLD = 3;
34389
34412
  const KANA_CHARS_PER_TOKEN = 1.35;
34390
34413
  const DEFAULT_LANGUAGE_CONFIGS = [
34391
34414
  {
34392
- pattern: /[äöüßẞ]/i,
34415
+ pattern: /[\u00E4\u00F6\u00FC\u00DF\u1E9E]/i,
34393
34416
  averageCharsPerToken: 2.6
34394
34417
  },
34395
34418
  {
34396
- pattern: /[éèêëàâîïôûùüÿçœæáíóúñ]/i,
34419
+ pattern: /[\u00E9\u00E8\u00EA\u00EB\u00E0\u00E2\u00EE\u00EF\u00F4\u00FB\u00F9\u00FC\u00FF\u00E7\u0153\u00E6\u00E1\u00ED\u00F3\u00FA\u00F1]/i,
34397
34420
  averageCharsPerToken: 3
34398
34421
  },
34399
34422
  {
34400
- pattern: /[ąćęłńóśźżěščřžýůúďťň]/i,
34423
+ pattern: /[\u0105\u0107\u0119\u0142\u0144\u00F3\u015B\u017A\u017C\u011B\u0161\u010D\u0159\u017E\u00FD\u016F\u00FA\u010F\u0165\u0148]/i,
34401
34424
  averageCharsPerToken: 2.5
34402
34425
  },
34403
34426
  {
@@ -34473,7 +34496,7 @@ const OBSERVER_TOOL_ARGUMENT_MAX_DEPTH = 5;
34473
34496
  const OBSERVER_TOOL_ARGUMENT_MAX_ENTRIES_PER_CONTAINER = 20;
34474
34497
  const OBSERVER_TOOL_ARGUMENT_MAX_OUTLINE_ENTRIES = 100;
34475
34498
  const OBSERVER_TOOL_ARGUMENT_MAX_PATH_CHARS = 160;
34476
- function isObjectLike$1(value) {
34499
+ function isObjectLike(value) {
34477
34500
  return typeof value === "object" && value !== null;
34478
34501
  }
34479
34502
  function sanitizeSurrogates(value) {
@@ -34485,10 +34508,10 @@ function sanitizeSurrogates(value) {
34485
34508
  if (next >= 56320 && next <= 57343) {
34486
34509
  sanitized += value.charAt(index) + value.charAt(index + 1);
34487
34510
  index++;
34488
- } else sanitized += "�";
34511
+ } else sanitized += "\uFFFD";
34489
34512
  continue;
34490
34513
  }
34491
- sanitized += code >= 56320 && code <= 57343 ? "�" : value[index];
34514
+ sanitized += code >= 56320 && code <= 57343 ? "\uFFFD" : value[index];
34492
34515
  }
34493
34516
  return sanitized;
34494
34517
  }
@@ -34510,7 +34533,7 @@ function truncatePath(path) {
34510
34533
  const headLength = 50;
34511
34534
  const tailLength = 60;
34512
34535
  const omitted = path.length - headLength - tailLength;
34513
- return `${safeSlice(path, headLength)}…[${omitted} chars; ${stablePathDigest(path)}]…${safeTail(path, tailLength)}`;
34536
+ return `${safeSlice(path, headLength)}\u2026[${omitted} chars; ${stablePathDigest(path)}]\u2026${safeTail(path, tailLength)}`;
34514
34537
  }
34515
34538
  function formatPath(parent, key, isArray) {
34516
34539
  if (isArray) return truncatePath(`${parent}[${key}]`);
@@ -34619,7 +34642,7 @@ function selectOutlineEntries(entries, limits) {
34619
34642
  const rendered = joinEntries(selected, marker);
34620
34643
  if (fits(rendered, limits)) return rendered;
34621
34644
  if (fits(marker, limits)) return marker;
34622
- return fits("…", limits) ? "…" : "";
34645
+ return fits("\u2026", limits) ? "\u2026" : "";
34623
34646
  }
34624
34647
  function indentPreview(value) {
34625
34648
  return value.split("\n").map((line) => ` | ${line}`).join("\n");
@@ -34659,16 +34682,16 @@ function formatToolArgumentsForObserver(value, options) {
34659
34682
  maxCharacters: options?.maxCharacters ?? Number.POSITIVE_INFINITY
34660
34683
  };
34661
34684
  if (limits.maxTokens <= 0 || limits.maxCharacters <= 0) return "";
34662
- if (!isObjectLike$1(value)) {
34685
+ if (!isObjectLike(value)) {
34663
34686
  if (typeof value !== "string" || value.length <= OBSERVER_TOOL_ARGUMENT_INLINE_STRING_MAX_CHARS) {
34664
34687
  const primitive = formatPrimitive(value);
34665
- return fits(primitive, limits) ? primitive : fits("…", limits) ? "…" : "";
34688
+ return fits(primitive, limits) ? primitive : fits("\u2026", limits) ? "\u2026" : "";
34666
34689
  }
34667
34690
  const summary = `<string, ${value.length} characters; preview size-limited>`;
34668
34691
  const rendered = appendWithinBudget(summary, formatPreview("preview", value, limits, summary), limits);
34669
34692
  if (rendered) return rendered;
34670
34693
  if (fits(summary, limits)) return summary;
34671
- return fits("…", limits) ? "…" : "";
34694
+ return fits("\u2026", limits) ? "\u2026" : "";
34672
34695
  }
34673
34696
  const outline = [];
34674
34697
  const previews = [];
@@ -34738,7 +34761,7 @@ function formatToolArgumentsForObserver(value, options) {
34738
34761
  });
34739
34762
  continue;
34740
34763
  }
34741
- if (!isObjectLike$1(entryValue)) {
34764
+ if (!isObjectLike(entryValue)) {
34742
34765
  outline.push({
34743
34766
  text: `${path}: ${formatPrimitive(entryValue)}`,
34744
34767
  depth: current.depth,
@@ -34819,28 +34842,22 @@ function formatToolArgumentsForObserver(value, options) {
34819
34842
  }
34820
34843
  const ENCRYPTED_CONTENT_KEY = "encryptedContent";
34821
34844
  const ENCRYPTED_CONTENT_REDACTION_THRESHOLD = 256;
34822
- function isObjectLike(value) {
34823
- return typeof value === "object" && value !== null;
34824
- }
34825
- function sanitizeToolResultValue(value, seen = /* @__PURE__ */ new WeakMap()) {
34826
- if (!isObjectLike(value)) return value;
34827
- if (seen.has(value)) return seen.get(value);
34828
- if (Array.isArray(value)) {
34829
- const sanitizedArray = [];
34830
- seen.set(value, sanitizedArray);
34831
- for (const item of value) sanitizedArray.push(sanitizeToolResultValue(item, seen));
34832
- return sanitizedArray;
34833
- }
34834
- const sanitizedObject = {};
34835
- seen.set(value, sanitizedObject);
34836
- for (const [key, entry] of Object.entries(value)) {
34837
- if (key === ENCRYPTED_CONTENT_KEY && typeof entry === "string" && entry.length > ENCRYPTED_CONTENT_REDACTION_THRESHOLD) {
34838
- sanitizedObject[key] = `[stripped encryptedContent: ${entry.length} characters]`;
34839
- continue;
34840
- }
34841
- sanitizedObject[key] = sanitizeToolResultValue(entry, seen);
34845
+ /** The string a boxed `String` serializes to; JSON.stringify unboxes it only after the replacer has run. */
34846
+ function unboxedString(value) {
34847
+ if (typeof value === "string") return value;
34848
+ if (typeof value !== "object" || value === null) return void 0;
34849
+ try {
34850
+ String.prototype.valueOf.call(value);
34851
+ } catch {
34852
+ return;
34842
34853
  }
34843
- return sanitizedObject;
34854
+ return String(value);
34855
+ }
34856
+ /** Redacts long `encryptedContent` strings: opaque provider data that would otherwise dominate the count. */
34857
+ function redactEncryptedContent(key, value) {
34858
+ if (key !== ENCRYPTED_CONTENT_KEY) return value;
34859
+ const text = unboxedString(value);
34860
+ return text !== void 0 && text.length > ENCRYPTED_CONTENT_REDACTION_THRESHOLD ? `[stripped encryptedContent: ${text.length} characters]` : value;
34844
34861
  }
34845
34862
  /**
34846
34863
  * Serializes a tool result without truncating it.
@@ -34860,14 +34877,20 @@ function serializeToolResultForTokenCounting(value) {
34860
34877
  function toolErrorTextToString(errorText) {
34861
34878
  return errorText == null ? "" : stringifyToolResult(errorText);
34862
34879
  }
34880
+ /**
34881
+ * Serializes with `JSON.stringify` itself, the serializer storage uses, so a count of this text describes what
34882
+ * storage holds and a reload reads back (`toJSON()`, boxed primitives, class instances, array indices).
34883
+ */
34863
34884
  function stringifyToolResult(value) {
34864
34885
  if (typeof value === "string") return value;
34865
- const sanitized = sanitizeToolResultValue(value);
34886
+ let json;
34866
34887
  try {
34867
- return JSON.stringify(sanitized, null, 2);
34888
+ json = JSON.stringify(value, redactEncryptedContent, 2);
34868
34889
  } catch {
34869
- return String(sanitized);
34890
+ return String(value);
34870
34891
  }
34892
+ if (json === void 0) return "";
34893
+ return json.startsWith("\"") ? JSON.parse(json) : json;
34871
34894
  }
34872
34895
  function resolveToolResultValue(part, invocationResult) {
34873
34896
  const mastraMetadata = part?.providerMetadata?.mastra;
@@ -34881,13 +34904,58 @@ function resolveToolResultValue(part, invocationResult) {
34881
34904
  usingStoredModelOutput: false
34882
34905
  };
34883
34906
  }
34907
+ const PREFIX_CHUNK_MIN_LENGTH = 256;
34908
+ function isAsciiAlphanumeric(code) {
34909
+ return code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122;
34910
+ }
34911
+ function isSplitWhitespace(code) {
34912
+ return code === 32 || code === 10 || code === 9 || code === 13;
34913
+ }
34914
+ /**
34915
+ * Returns a function that counts `estimateTokenCount(text.slice(0, end) + suffix)` without rescanning the
34916
+ * whole prefix on every call.
34917
+ *
34918
+ * tokenx splits text into segments on whitespace and punctuation runs and sums a per-segment estimate.
34919
+ * Letters and digits are never separators and whitespace always is, so the position between an ASCII
34920
+ * letter or digit and a following whitespace character is always a segment boundary: the count of any
34921
+ * string that shares the text up to such a position equals the count before it plus the count after it.
34922
+ * The text is cut at those boundaries once, and each call only rescans the chunk it ends in.
34923
+ */
34924
+ function createPrefixTokenCounter(text) {
34925
+ const boundaries = [0];
34926
+ const tokensBefore = [0];
34927
+ let chunkStart = 0;
34928
+ let runningTokens = 0;
34929
+ for (let i = PREFIX_CHUNK_MIN_LENGTH; i < text.length; i++) if (i - chunkStart >= PREFIX_CHUNK_MIN_LENGTH && isSplitWhitespace(text.charCodeAt(i)) && isAsciiAlphanumeric(text.charCodeAt(i - 1))) {
34930
+ runningTokens += estimateTokenCount(text.slice(chunkStart, i));
34931
+ boundaries.push(i);
34932
+ tokensBefore.push(runningTokens);
34933
+ chunkStart = i;
34934
+ }
34935
+ return (end, suffix = "") => {
34936
+ let low = 0;
34937
+ let high = boundaries.length - 1;
34938
+ while (low < high) {
34939
+ const mid = low + high + 1 >> 1;
34940
+ if (boundaries[mid] <= end) low = mid;
34941
+ else high = mid - 1;
34942
+ }
34943
+ return tokensBefore[low] + estimateTokenCount(text.slice(boundaries[low], end) + suffix);
34944
+ };
34945
+ }
34884
34946
  function truncateStringByTokens(text, maxTokens) {
34885
34947
  if (!text || maxTokens <= 0) return "";
34886
- const totalTokens = estimateTokenCount(text);
34948
+ const countPrefixTokens = createPrefixTokenCounter(text);
34949
+ const totalTokens = countPrefixTokens(text.length);
34887
34950
  if (totalTokens <= maxTokens) return text;
34888
34951
  const buildCandidate = (sliceEnd) => {
34889
- const visible = safeSlice(text, sliceEnd);
34890
- return `${visible}\n... [truncated ~${totalTokens - estimateTokenCount(visible)} tokens]`;
34952
+ const visibleEnd = safeSlice(text, sliceEnd).length;
34953
+ const suffix = `\n... [truncated ~${totalTokens - countPrefixTokens(visibleEnd)} tokens]`;
34954
+ return {
34955
+ visibleEnd,
34956
+ suffix,
34957
+ tokens: countPrefixTokens(visibleEnd, suffix)
34958
+ };
34891
34959
  };
34892
34960
  let low = 0;
34893
34961
  let high = text.length;
@@ -34895,12 +34963,12 @@ function truncateStringByTokens(text, maxTokens) {
34895
34963
  while (low <= high) {
34896
34964
  const mid = Math.floor((low + high) / 2);
34897
34965
  const candidate = buildCandidate(mid);
34898
- if (estimateTokenCount(candidate) <= maxTokens) {
34966
+ if (candidate.tokens <= maxTokens) {
34899
34967
  best = candidate;
34900
34968
  low = mid + 1;
34901
34969
  } else high = mid - 1;
34902
34970
  }
34903
- return best;
34971
+ return text.slice(0, best.visibleEnd) + best.suffix;
34904
34972
  }
34905
34973
  function formatToolResultForObserver(value, options) {
34906
34974
  return truncateStringByTokens(stringifyToolResult(value), options?.maxTokens ?? 5e3);
@@ -34912,24 +34980,24 @@ function formatToolResultForObserver(value, options) {
34912
34980
  const OBSERVER_EXTRACTION_INSTRUCTIONS = `CRITICAL: DISTINGUISH USER ASSERTIONS FROM QUESTIONS
34913
34981
 
34914
34982
  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
34983
+ - "I have two kids" \u2192 \u{1F534} (14:30) User stated has two kids
34984
+ - "I work at Acme Corp" \u2192 \u{1F534} (14:31) User stated works at Acme Corp
34985
+ - "I graduated in 2019" \u2192 \u{1F534} (14:32) User stated graduated in 2019
34918
34986
 
34919
34987
  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
34988
+ - "Can you help me with X?" \u2192 \u{1F534} (15:00) User asked help with X
34989
+ - "What's the best way to do Y?" \u2192 \u{1F534} (15:01) User asked best way to do Y
34922
34990
 
34923
34991
  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)")
34992
+ - "Can you recommend..." \u2192 Question (extract as "User asked...")
34993
+ - "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)")
34994
+ - "I need to [do X]" \u2192 Statement of intent (extract as "User stated they need to [do X] (again, add date if mentioned)")
34927
34995
 
34928
34996
  STATE CHANGES AND UPDATES:
34929
34997
  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)"
34998
+ - "I'm going to start doing X instead of Y" \u2192 "User will start doing X (changing from Y)"
34999
+ - "I'm switching from A to B" \u2192 "User is switching from A to B"
35000
+ - "I moved my stuff to the new place" \u2192 "User moved their stuff to the new place (no longer at previous location)"
34933
35001
 
34934
35002
  If the new state contradicts or updates previous information, make that explicit:
34935
35003
  - BAD: "User plans to use the new method"
@@ -35020,11 +35088,11 @@ BAD: User got something.
35020
35088
  GOOD: User purchased / received / was given something. (be specific)
35021
35089
 
35022
35090
  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"
35091
+ - "getting" something regularly \u2192 "subscribed to" or "enrolled in"
35092
+ - "getting" something once \u2192 "purchased" or "acquired"
35093
+ - "got" \u2192 "purchased", "received as gift", "was given", "picked up"
35094
+ - "signed up" \u2192 "enrolled in", "registered for", "subscribed to"
35095
+ - "stopped getting" \u2192 "canceled", "unsubscribed from", "discontinued"
35028
35096
 
35029
35097
  When the assistant interprets or confirms the user's vague language, prefer the assistant's precise terminology.
35030
35098
 
@@ -35109,16 +35177,16 @@ AVOIDING REPETITIVE OBSERVATIONS:
35109
35177
  - Do NOT repeat the same observation across multiple turns if there is no new information.
35110
35178
  - 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
35179
 
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
35180
+ Example \u2014 BAD (repetitive):
35181
+ * \u{1F7E1} (14:30) Agent used view tool on src/auth.ts
35182
+ * \u{1F7E1} (14:31) Agent used view tool on src/users.ts
35183
+ * \u{1F7E1} (14:32) Agent used view tool on src/routes.ts
35116
35184
 
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
35185
+ Example \u2014 GOOD (grouped):
35186
+ * \u{1F7E1} (14:30) Agent browsed source files for auth flow
35187
+ * -> viewed src/auth.ts \u2014 found token validation logic
35188
+ * -> viewed src/users.ts \u2014 found user lookup by email
35189
+ * -> viewed src/routes.ts \u2014 found middleware chain
35122
35190
 
35123
35191
  Only add a new observation for a repeated action if the NEW result changes the picture.
35124
35192
 
@@ -35131,29 +35199,29 @@ COMPLETION TRACKING:
35131
35199
  Completion observations are not just summaries. They are explicit memory signals to the assistant that a task, question, or subtask has been resolved.
35132
35200
  Without clear completion markers, the assistant may forget that work is already finished and may repeat, reopen, or continue an already-completed task.
35133
35201
 
35134
- Use ✅ to answer: "What exactly is now done?"
35202
+ Use \u2705 to answer: "What exactly is now done?"
35135
35203
  Choose completion observations that help the assistant know what is finished and should not be reworked unless new information appears.
35136
35204
 
35137
- Use ✅ when:
35205
+ Use \u2705 when:
35138
35206
  - The user explicitly confirms something worked or was answered ("thanks, that fixed it", "got it", "perfect")
35139
35207
  - The assistant provided a definitive, complete answer to a factual question and the user moved on
35140
35208
  - A multi-step task reached its stated goal
35141
35209
  - The user acknowledged receipt of requested information
35142
35210
  - A concrete subtask, fix, deliverable, or implementation step became complete during ongoing work
35143
35211
 
35144
- Do NOT use ✅ when:
35145
- - The assistant merely responded — the user might follow up with corrections
35212
+ Do NOT use \u2705 when:
35213
+ - The assistant merely responded \u2014 the user might follow up with corrections
35146
35214
  - The topic is paused but not resolved ("I'll try that later")
35147
35215
  - The user's reaction is ambiguous
35148
35216
 
35149
35217
  FORMAT:
35150
35218
  As a sub-bullet under the related observation group:
35151
- * 🔴 (14:30) User asked how to configure auth middleware
35219
+ * \u{1F534} (14:30) User asked how to configure auth middleware
35152
35220
  * -> Agent explained JWT setup with code example
35153
- * ✅ User confirmed auth is working
35221
+ * \u2705 User confirmed auth is working
35154
35222
 
35155
35223
  Or as a standalone observation when closing out a broader task:
35156
- * ✅ (14:45) Auth configuration task completed — user confirmed middleware is working
35224
+ * \u2705 (14:45) Auth configuration task completed \u2014 user confirmed middleware is working
35157
35225
 
35158
35226
  Completion observations should be terse but specific about WHAT was completed.
35159
35227
  Prefer concrete resolved outcomes over abstract workflow status so the assistant remembers what is already done.`;
@@ -35170,28 +35238,28 @@ buildObserverOutputFormat();
35170
35238
  */
35171
35239
  function buildObserverOutputFormat(extractors) {
35172
35240
  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
35241
+ - \u{1F534} High: explicit user facts, preferences, unresolved goals, critical context
35242
+ - \u{1F7E1} Medium: project details, learned information, tool results
35243
+ - \u{1F7E2} Low: minor details, uncertain observations
35244
+ - \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
35245
 
35178
35246
  Group related observations (like tool sequences) by indenting:
35179
- * 🔴 (14:33) Agent debugging auth issue
35247
+ * \u{1F534} (14:33) Agent debugging auth issue
35180
35248
  * -> ran git status, found 3 modified files
35181
35249
  * -> viewed auth.ts:45-60, found missing null check
35182
35250
  * -> applied fix, tests now pass
35183
- * ✅ Tests passing, auth issue resolved
35251
+ * \u2705 Tests passing, auth issue resolved
35184
35252
 
35185
35253
  Group observations by date. Within a date, list observations in the order the events happened (not by importance), each with 24-hour time.
35186
35254
 
35187
35255
  <observations>
35188
35256
  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
35257
+ * \u{1F534} (14:30) User prefers direct answers
35258
+ * \u{1F534} (14:31) Working on feature X
35259
+ * \u{1F7E1} (14:32) User might prefer dark mode
35192
35260
 
35193
35261
  Date: Dec 5, 2025
35194
- * 🔴 (09:15) Continued work on feature X
35262
+ * \u{1F534} (09:15) Continued work on feature X
35195
35263
  </observations>
35196
35264
 
35197
35265
  ${buildExtractorOutputSections(extractors ?? []) || (extractors === void 0 ? `
@@ -35221,9 +35289,9 @@ const OBSERVER_GUIDELINES = `- Be specific enough for the assistant to act on
35221
35289
  - If the agent calls tools, observe what was called, why, and what was learned
35222
35290
  - When observing files with line numbers, include the line number if useful
35223
35291
  - 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
35292
+ - Make sure you start each observation with a priority emoji (\u{1F534}, \u{1F7E1}, \u{1F7E2}) or a completion marker (\u2705)
35293
+ - 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}
35294
+ - Treat \u2705 as a memory signal that tells the assistant something is finished and should not be repeated unless new information changes it
35227
35295
  - Make completion observations answer "What exactly is now done?"
35228
35296
  - Prefer concrete resolved outcomes over meta-level workflow or bookkeeping updates
35229
35297
  - When multiple concrete things were completed, capture the concrete completed work rather than collapsing it into a vague progress summary
@@ -35277,8 +35345,8 @@ For multi-thread output, wrap each thread's observations like this:
35277
35345
  <observations>
35278
35346
  <thread id="thread_id_1">
35279
35347
  Date: Dec 4, 2025
35280
- * 🔴 (14:30) User prefers direct answers
35281
- * 🔴 (14:31) Working on feature X${currentTaskEnabled ? `
35348
+ * \u{1F534} (14:30) User prefers direct answers
35349
+ * \u{1F534} (14:31) Working on feature X${currentTaskEnabled ? `
35282
35350
 
35283
35351
  <current-task>
35284
35352
  What the agent is currently working on in this thread
@@ -35291,7 +35359,7 @@ Hint for the agent's next message in this thread
35291
35359
 
35292
35360
  <thread id="thread_id_2">
35293
35361
  Date: Dec 5, 2025
35294
- * 🔴 (09:15) User asked about deployment${currentTaskEnabled ? `
35362
+ * \u{1F534} (09:15) User asked about deployment${currentTaskEnabled ? `
35295
35363
 
35296
35364
  <current-task>
35297
35365
  Current task for this thread
@@ -36122,7 +36190,7 @@ function sanitizeObservationLines(observations) {
36122
36190
  const lines = observations.split("\n");
36123
36191
  let changed = false;
36124
36192
  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]";
36193
+ lines[i] = safeSlice(lines[i], MAX_OBSERVATION_LINE_CHARS) + " \u2026 [truncated]";
36126
36194
  changed = true;
36127
36195
  }
36128
36196
  return changed ? lines.join("\n") : observations;
@@ -36320,8 +36388,8 @@ function describeDegenerateOutput(text, snippetChars = 400) {
36320
36388
  */
36321
36389
  function optimizeObservationsForContext(observations) {
36322
36390
  let optimized = stripEphemeralAnchorIds(observations);
36323
- optimized = optimized.replace(/🟡\s*/g, "");
36324
- optimized = optimized.replace(/🟢\s*/g, "");
36391
+ optimized = optimized.replace(/\uD83D\uDFE1\s*/g, "");
36392
+ optimized = optimized.replace(/\uD83D\uDFE2\s*/g, "");
36325
36393
  optimized = optimized.replace(/\s*->\s*/g, " ");
36326
36394
  optimized = optimized.replace(/ +/g, " ");
36327
36395
  optimized = optimized.replace(/\n{3,}/g, "\n\n");
@@ -37116,9 +37184,24 @@ function mergeCacheEntry(cache, key, entry) {
37116
37184
  function getPartCacheEntry(part, key) {
37117
37185
  return getCacheEntry(getPartMastraMetadata(part)?.tokenEstimate, key);
37118
37186
  }
37187
+ /**
37188
+ * Parts this process gave a new stored count. A part loaded from storage with its count is never in here,
37189
+ * so a message holding one of these parts has a count storage does not have yet.
37190
+ */
37191
+ const partsWithUnsavedCount = /* @__PURE__ */ new WeakSet();
37192
+ /** Whether `part` gained a stored count in this process that has not been handed to a save yet. */
37193
+ function hasUnsavedTokenEstimate(part) {
37194
+ return typeof part === "object" && part !== null && partsWithUnsavedCount.has(part);
37195
+ }
37196
+ /** Note that `part`'s count is on its way to storage, so later steps do not save it again. */
37197
+ function markTokenEstimateSaved(part) {
37198
+ if (typeof part === "object" && part !== null) partsWithUnsavedCount.delete(part);
37199
+ }
37200
+ const partCountMemo = /* @__PURE__ */ new WeakMap();
37119
37201
  function setPartCacheEntry(part, key, entry) {
37120
37202
  const mastraMetadata = ensurePartMastraMetadata(part);
37121
37203
  mastraMetadata.tokenEstimate = mergeCacheEntry(mastraMetadata.tokenEstimate, key, entry);
37204
+ partsWithUnsavedCount.add(part);
37122
37205
  }
37123
37206
  /**
37124
37207
  * Extracts a caller-supplied token estimate stamped on a part via
@@ -37277,7 +37360,7 @@ async function resolveImageDimensionsAsync(part) {
37277
37360
  const url = resolveHttpAssetUrl(getObjectValue(part, "image") ?? getObjectValue(part, "data"));
37278
37361
  if (!url) return existing;
37279
37362
  try {
37280
- const probeImageSize = (await import("./probe-image-size-DBCcUUw_.js").then((m) => /* @__PURE__ */ __toESM$1(m.default, 1))).default;
37363
+ const probeImageSize = (await import("./probe-image-size-zXQBlFaQ.js").then((m) => /* @__PURE__ */ __toESM$1(m.default, 1))).default;
37281
37364
  const probed = await probeImageSize(url, {
37282
37365
  open_timeout: REMOTE_IMAGE_PROBE_TIMEOUT_MS,
37283
37366
  response_timeout: REMOTE_IMAGE_PROBE_TIMEOUT_MS,
@@ -37812,14 +37895,19 @@ async function fetchGoogleAttachmentTokenEstimate(modelId, part) {
37812
37895
  * undercounted as generic JSON blobs.
37813
37896
  */
37814
37897
  var TokenCounter = class TokenCounter {
37815
- cacheSource;
37898
+ /**
37899
+ * Stored counts belong to the stock estimator. A subclass or instance that overrides `countString`
37900
+ * reads and writes its own namespace, so it never reuses a count the stock estimator saved.
37901
+ */
37902
+ get cacheSource() {
37903
+ return this.countString === TokenCounter.prototype.countString ? `v${TOKEN_ESTIMATE_CACHE_VERSION}:${resolveEstimatorId()}` : `v${TOKEN_ESTIMATE_CACHE_VERSION}:custom`;
37904
+ }
37816
37905
  defaultModelContext;
37817
37906
  inFlightAttachmentCounts = /* @__PURE__ */ new Map();
37818
37907
  multimodalToolResultCounts = /* @__PURE__ */ new WeakMap();
37819
37908
  static TOKENS_PER_MESSAGE = 3.8;
37820
37909
  static TOKENS_PER_CONVERSATION = 24;
37821
37910
  constructor(options) {
37822
- this.cacheSource = `v${TOKEN_ESTIMATE_CACHE_VERSION}:${resolveEstimatorId()}`;
37823
37911
  this.defaultModelContext = parseModelContext(options?.model);
37824
37912
  }
37825
37913
  runWithModelContext(model, fn) {
@@ -37850,6 +37938,28 @@ var TokenCounter = class TokenCounter {
37850
37938
  });
37851
37939
  return tokens;
37852
37940
  }
37941
+ /**
37942
+ * Count one content-only piece of a part (its text, a tool's args or result) the same way as
37943
+ * {@link readOrPersistPartEstimate}: a stored count is reused only when its content hash matches.
37944
+ * `refs` are the values the payload is built from. While the same part object still holds the same
37945
+ * refs, the count from the last call is returned without serializing or hashing again, so a part
37946
+ * counted by `getStatus` and then by the next step is hashed once per process.
37947
+ * Only string refs are memoized (object payloads are hashed every time, since they can change in place).
37948
+ */
37949
+ readOrPersistMemoizedPartEstimate(part, kind, refs, getPayload) {
37950
+ if (!refs.every((ref) => typeof ref === "string")) return this.readOrPersistPartEstimate(part, kind, getPayload());
37951
+ let byKind = partCountMemo.get(part);
37952
+ const memo = byKind?.get(kind);
37953
+ if (memo && memo.owner === this && memo.refs.length === refs.length && memo.refs.every((ref, i) => ref === refs[i])) return memo.tokens;
37954
+ const tokens = this.readOrPersistPartEstimate(part, kind, getPayload());
37955
+ if (!byKind) partCountMemo.set(part, byKind = /* @__PURE__ */ new Map());
37956
+ byKind.set(kind, {
37957
+ owner: this,
37958
+ refs,
37959
+ tokens
37960
+ });
37961
+ return tokens;
37962
+ }
37853
37963
  readOrPersistFixedPartEstimate(part, kind, payload, tokens) {
37854
37964
  const key = buildEstimateKey(kind, payload);
37855
37965
  const cached = getPartCacheEntry(part, key);
@@ -38200,18 +38310,23 @@ var TokenCounter = class TokenCounter {
38200
38310
  /**
38201
38311
  * Count the name and the arguments of a tool call. Every state before the tool produces an
38202
38312
  * output holds the same call signature in the context window, so all of those states share
38203
- * these cache kinds. `buildEstimateKey` hashes the text, so a shared kind stays correct and
38204
- * keeps the estimate warm while the invocation moves from one state to the next.
38313
+ * these cache kinds, and the estimate stays warm while the invocation moves from one state to
38314
+ * the next. Name and args don't change across those states once the call stops streaming.
38205
38315
  */
38206
38316
  countToolCallSignature(part, invocation) {
38207
38317
  let tokens = 0;
38208
38318
  let overheadDelta = 0;
38209
- if (invocation.toolName) tokens += this.readOrPersistPartEstimate(part, "tool-call-name", invocation.toolName);
38319
+ const storable = invocation.state !== "partial-call";
38320
+ const count = (kind, ref, getPayload) => storable ? this.readOrPersistMemoizedPartEstimate(part, kind, [ref], getPayload) : this.readOrPersistPartEstimate(part, kind, getPayload());
38321
+ if (invocation.toolName) {
38322
+ const toolName = invocation.toolName;
38323
+ tokens += count("tool-call-name", toolName, () => toolName);
38324
+ }
38210
38325
  if (invocation.args !== void 0) {
38211
- if (typeof invocation.args === "string") tokens += this.readOrPersistPartEstimate(part, "tool-call-args", invocation.args);
38326
+ const args = invocation.args;
38327
+ if (typeof args === "string") tokens += count("tool-call-args", args, () => args);
38212
38328
  else {
38213
- const argsJson = JSON.stringify(invocation.args);
38214
- tokens += this.readOrPersistPartEstimate(part, "tool-call-args-json", argsJson);
38329
+ tokens += count("tool-call-args-json", args, () => JSON.stringify(args));
38215
38330
  overheadDelta -= 12;
38216
38331
  }
38217
38332
  }
@@ -38223,11 +38338,14 @@ var TokenCounter = class TokenCounter {
38223
38338
  countNonAttachmentPart(part) {
38224
38339
  let overheadDelta = 0;
38225
38340
  let extraMessageDelta = 0;
38226
- if (part.type === "text") return {
38227
- tokens: this.readOrPersistPartEstimate(part, "text", part.text),
38228
- overheadDelta,
38229
- extraMessageDelta
38230
- };
38341
+ if (part.type === "text") {
38342
+ const text = part.text;
38343
+ return {
38344
+ tokens: this.readOrPersistMemoizedPartEstimate(part, "text", [text], () => text),
38345
+ overheadDelta,
38346
+ extraMessageDelta
38347
+ };
38348
+ }
38231
38349
  if (part.type === "tool-invocation") {
38232
38350
  const invocation = part.toolInvocation;
38233
38351
  const state = invocation.state;
@@ -38246,7 +38364,7 @@ var TokenCounter = class TokenCounter {
38246
38364
  tokens += signature.tokens;
38247
38365
  overheadDelta += signature.overheadDelta;
38248
38366
  const reason = invocation.approval?.reason;
38249
- if (reason) tokens += this.readOrPersistPartEstimate(part, "tool-approval-reason", reason);
38367
+ if (reason) tokens += this.readOrPersistMemoizedPartEstimate(part, "tool-approval-reason", [reason], () => reason);
38250
38368
  return {
38251
38369
  tokens,
38252
38370
  overheadDelta,
@@ -38262,15 +38380,12 @@ var TokenCounter = class TokenCounter {
38262
38380
  if (resultForCounting !== void 0 && (typeof resultForCounting !== "string" || resultForCounting.trim().length > 0)) {
38263
38381
  const contentTokens = this.countMultimodalToolResultContent(part, resultForCounting);
38264
38382
  if (contentTokens !== void 0) tokens += contentTokens;
38265
- else {
38266
- const formattedResult = serializeToolResultForTokenCounting(resultForCounting);
38267
- tokens += this.readOrPersistPartEstimate(part, usingStoredModelOutput ? "tool-result-model-output-json" : "tool-result-json", formattedResult);
38268
- }
38383
+ else tokens += this.readOrPersistMemoizedPartEstimate(part, usingStoredModelOutput ? "tool-result-model-output-json" : "tool-result-json", [resultForCounting], () => serializeToolResultForTokenCounting(resultForCounting));
38269
38384
  if (typeof resultForCounting !== "string") overheadDelta -= 12;
38270
38385
  } else {
38271
38386
  const errorText = toolErrorTextToString(invocation.errorText);
38272
38387
  const fallback = invocation.isError ? errorText.trim() ? errorText : "Tool execution failed" : "[empty result]";
38273
- tokens += this.readOrPersistPartEstimate(part, invocation.isError ? "tool-result-error" : "tool-result-json", fallback);
38388
+ tokens += this.readOrPersistMemoizedPartEstimate(part, invocation.isError ? "tool-result-error" : "tool-result-json", [fallback], () => fallback);
38274
38389
  }
38275
38390
  return {
38276
38391
  tokens,
@@ -38284,7 +38399,7 @@ var TokenCounter = class TokenCounter {
38284
38399
  tokens += signature.tokens;
38285
38400
  overheadDelta += signature.overheadDelta;
38286
38401
  const reason = invocation.approval?.reason?.trim() ? invocation.approval.reason : "Tool call was not approved by the user";
38287
- tokens += this.readOrPersistPartEstimate(part, "tool-result-denied", reason);
38402
+ tokens += this.readOrPersistMemoizedPartEstimate(part, "tool-result-denied", [reason], () => reason);
38288
38403
  return {
38289
38404
  tokens,
38290
38405
  overheadDelta,
@@ -38298,7 +38413,7 @@ var TokenCounter = class TokenCounter {
38298
38413
  overheadDelta += signature.overheadDelta;
38299
38414
  const errorText = toolErrorTextToString(invocation.errorText);
38300
38415
  const errorMessage = errorText.trim() ? errorText : "Tool execution failed";
38301
- tokens += this.readOrPersistPartEstimate(part, "tool-result-error", errorMessage);
38416
+ tokens += this.readOrPersistMemoizedPartEstimate(part, "tool-result-error", [errorMessage], () => errorMessage);
38302
38417
  return {
38303
38418
  tokens,
38304
38419
  overheadDelta,
@@ -38311,6 +38426,11 @@ var TokenCounter = class TokenCounter {
38311
38426
  overheadDelta,
38312
38427
  extraMessageDelta
38313
38428
  };
38429
+ if (part.type === "step-start") return {
38430
+ tokens: 0,
38431
+ overheadDelta,
38432
+ extraMessageDelta
38433
+ };
38314
38434
  if (part.type === "reasoning") return {
38315
38435
  tokens: 0,
38316
38436
  overheadDelta,
@@ -38599,8 +38719,8 @@ const updateWorkingMemoryTool = (memoryConfig) => {
38599
38719
  }
38600
38720
  const usesMergeSemantics = Boolean(schema);
38601
38721
  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.`;
38722
+ 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.`;
38723
+ 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
38724
  return createTool({
38605
38725
  id: "update-working-memory",
38606
38726
  description,
@@ -39610,8 +39730,8 @@ async function pageGroups({ om, threadId, resourceId, groupId, recordId, directi
39610
39730
  })).count > 0;
39611
39731
  const hasLater = direction === "before" || hasMore;
39612
39732
  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. —");
39733
+ 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");
39734
+ 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
39735
  text.unshift(`### Observation page\nThread: ${threadTitle || "(untitled)"}\nShowing ${page.length} groups ${requestedDirection === void 0 ? "starting at" : `strictly ${direction}`} \`${groupId}\` (oldest first).`);
39616
39736
  return {
39617
39737
  results: text.join("\n\n"),
@@ -39797,7 +39917,7 @@ async function listThreadsForResource({ memory, resourceId, currentThreadId, pag
39797
39917
  const title = thread.title || "(untitled)";
39798
39918
  const updated = formatTimestamp(thread.updatedAt);
39799
39919
  const created = formatTimestamp(thread.createdAt);
39800
- const marker = isCurrent ? " ← current" : "";
39920
+ const marker = isCurrent ? " \u2190 current" : "";
39801
39921
  lines.push(`- **${title}**${marker}`);
39802
39922
  lines.push(` id: ${thread.id}`);
39803
39923
  lines.push(` updated: ${updated} | created: ${created}`);
@@ -39976,7 +40096,7 @@ async function searchMessagesForResource({ memory, om, resourceId, currentThread
39976
40096
  const groupLine = match.groupId ? `- observation group: ${groupCursor(match.groupId, match.recordId)}` : void 0;
39977
40097
  const scoreLine = `- score: ${match.score.toFixed(2)}`;
39978
40098
  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)} —`);
40099
+ 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
40100
  if (suppression) {
39981
40101
  sections.push(`${groupLine}\n thread: ${match.threadId}; ${suppression}`);
39982
40102
  continue;
@@ -40531,7 +40651,7 @@ async function recallAttachmentView({ memory, threadId, resourceId, cursor, part
40531
40651
  const partType = rawPart?.type;
40532
40652
  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
40653
  const resolvedAttachment = resolveViewableAttachment(rawPart);
40534
- if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)} — ${resolvedAttachment.note}` };
40654
+ if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)} \u2014 ${resolvedAttachment.note}` };
40535
40655
  return { content: [{
40536
40656
  type: "text",
40537
40657
  text: formatAttachmentPart(partType, rawPart)
@@ -40934,7 +41054,7 @@ const recallTool = (_memoryConfig, options) => {
40934
41054
  if (!thread) return { error: "Could not resolve current thread." };
40935
41055
  if (isResourceScope && resourceId && thread.resourceId !== resourceId) throw new Error("Thread does not belong to the active resource");
40936
41056
  return {
40937
- threads: `- **${thread.title || "(untitled)"}** ← current\n id: ${thread.id}\n updated: ${formatTimestamp(thread.updatedAt)} | created: ${formatTimestamp(thread.createdAt)}`,
41057
+ threads: `- **${thread.title || "(untitled)"}** \u2190 current\n id: ${thread.id}\n updated: ${formatTimestamp(thread.updatedAt)} | created: ${formatTimestamp(thread.createdAt)}`,
40938
41058
  count: 1,
40939
41059
  page: 0,
40940
41060
  hasMore: false
@@ -41685,9 +41805,10 @@ const suggestedResponseInstructions = `Hint for the agent's immediate next messa
41685
41805
  - "The assistant should wait for the user to respond before continuing."
41686
41806
  - Call the view tool on src/example.ts to continue debugging.`;
41687
41807
  const threadTitleInstructions = `A short, noun-phrase title for this conversation (2-5 words). Examples:
41688
- - "Auth bug fix" — not "Fixing the auth bug"
41689
- - "Dark mode toggle" — not "User wants dark mode toggle added"
41690
- - "Deployment pipeline setup" — not "Setting up deployment pipeline for project"
41808
+ - "Auth bug fix" \u2014 not "Fixing the auth bug"
41809
+ - "Dark mode toggle" \u2014 not "User wants dark mode toggle added"
41810
+ - "Deployment pipeline setup" \u2014 not "Setting up deployment pipeline for project"
41811
+ Write the title in the same language the user's messages are written in.
41691
41812
  Only update when the topic meaningfully changes.`;
41692
41813
  function createCurrentTaskExtractor() {
41693
41814
  return new Extractor({
@@ -42757,7 +42878,7 @@ var SyncObservationStrategy = class extends ObservationStrategy {
42757
42878
  failures: result.extractionFailures,
42758
42879
  previousValues: this.priorExtractedValues,
42759
42880
  rawObservations: result.observations,
42760
- recentMessages: formatMessagesForObserver(this.opts.messages, {
42881
+ recentMessages: () => formatMessagesForObserver(this.opts.messages, {
42761
42882
  maxPartLength: 500,
42762
42883
  timeZone: this.opts.record.observedTimezone
42763
42884
  }),
@@ -42981,7 +43102,7 @@ var AsyncBufferObservationStrategy = class extends ObservationStrategy {
42981
43102
  failures: result.extractionFailures,
42982
43103
  previousValues: this.priorExtractedValues,
42983
43104
  rawObservations: result.observations,
42984
- recentMessages: formatMessagesForObserver(messages, {
43105
+ recentMessages: () => formatMessagesForObserver(messages, {
42985
43106
  maxPartLength: 500,
42986
43107
  timeZone: this.opts.record.observedTimezone
42987
43108
  }),
@@ -43410,7 +43531,7 @@ var ResourceScopedObservationStrategy = class extends ObservationStrategy {
43410
43531
  failures: result.extractionFailures,
43411
43532
  previousValues,
43412
43533
  rawObservations: result.observations,
43413
- recentMessages: formatMessagesForObserver(threadMessages, {
43534
+ recentMessages: () => formatMessagesForObserver(threadMessages, {
43414
43535
  maxPartLength: 500,
43415
43536
  timeZone: this.opts.record.observedTimezone
43416
43537
  }),
@@ -43639,13 +43760,54 @@ ObservationStrategy.create = ((om, opts) => {
43639
43760
  if (deps.scope === "resource" && opts.resourceId) return new ResourceScopedObservationStrategy(deps, opts);
43640
43761
  return new SyncObservationStrategy(deps, opts);
43641
43762
  });
43763
+ /**
43764
+ * Mark the stored history of `threadId` in `messageList` that OM gave new token counts, so the counts are saved
43765
+ * with the messages. Call the returned function once the counting is done: every message holding a part that
43766
+ * gained a count in this process is marked for resave, and the normal save writes it back whole. Counts made
43767
+ * before this is called (while the turn loaded history) are caught too.
43768
+ *
43769
+ * Only messages of `threadId` are marked. A message recalled from another thread of the resource is counted but
43770
+ * never written, because saving it would bump that thread's `updatedAt` and reorder the recent-thread list.
43771
+ *
43772
+ * A Core without `markForResave` is left alone: counting still works, the counts are just not saved.
43773
+ */
43774
+ function resaveCountedMessagesFor(messageList, threadId) {
43775
+ if (typeof messageList.markForResave !== "function") return () => {};
43776
+ return () => {
43777
+ for (const message of messageList.get.remembered.db()) {
43778
+ if (message.threadId !== threadId) continue;
43779
+ const parts = message.content?.parts ?? [];
43780
+ if (!parts.some(hasUnsavedTokenEstimate)) continue;
43781
+ messageList.markForResave(message);
43782
+ parts.forEach(markTokenEstimateSaved);
43783
+ }
43784
+ };
43785
+ }
43786
+ /** The stored messages marked for resave in `messageList`; none for a Core without `markForResave`. */
43787
+ function messagesMarkedForResave(messageList) {
43788
+ return typeof messageList.getMessagesToResave === "function" ? messageList.getMessagesToResave() : [];
43789
+ }
43790
+ /**
43791
+ * Ids of the stored messages marked for resave in `messageList` that are not in `ownMessages` (the turn's
43792
+ * own input and output). Those are saved whole; the rest only gained counts and are patched onto storage.
43793
+ */
43794
+ function idsMarkedForResave(messageList, ownMessages = []) {
43795
+ const own = new Set(ownMessages.map((message) => message.id));
43796
+ return new Set(messagesMarkedForResave(messageList).map((message) => message.id).filter((id) => !own.has(id)));
43797
+ }
43798
+ /** `messages` with the messages marked for resave added, each message once. */
43799
+ function withMessagesMarkedForResave(messageList, messages) {
43800
+ const ids = new Set(messages.map((message) => message.id));
43801
+ return [...messages, ...messagesMarkedForResave(messageList).filter((message) => !ids.has(message.id))];
43802
+ }
43642
43803
  async function loadMemoryContextMessages({ memory, messageList, threadId, resourceId, runState }) {
43643
43804
  const ctx = await memory.getContext({
43644
43805
  threadId,
43645
43806
  resourceId,
43646
43807
  runState
43647
43808
  });
43648
- for (const msg of ctx.messages) if (msg.role !== "system") messageList.add(msg, "memory");
43809
+ const messages = ctx.messages.filter((msg) => msg.role !== "system");
43810
+ if (messages.length) messageList.add(messages, "memory");
43649
43811
  return ctx;
43650
43812
  }
43651
43813
  function hasPendingToolCall(message) {
@@ -43739,7 +43901,7 @@ var ObservationStep = class {
43739
43901
  }
43740
43902
  /** Step context from prepare(). Throws if prepare() hasn't been called. */
43741
43903
  get context() {
43742
- if (!this._context) throw new Error("Step not prepared yet — call prepare() first");
43904
+ if (!this._context) throw new Error("Step not prepared yet \u2014 call prepare() first");
43743
43905
  return this._context;
43744
43906
  }
43745
43907
  /**
@@ -43850,7 +44012,7 @@ var ObservationStep = class {
43850
44012
  const inputIds = new Set(messageList.get.input.db().map((msg) => msg.id));
43851
44013
  const sealedOutput = safeCandidates.filter((msg) => !inputIds.has(msg.id));
43852
44014
  messageList.removeByIds(sealedOutput.map((msg) => msg.id));
43853
- for (const msg of sealedOutput) messageList.add(msg, "memory");
44015
+ if (sealedOutput.length) messageList.add(sealedOutput, "memory");
43854
44016
  }
43855
44017
  if (!deferred) {
43856
44018
  om.trackBackgroundWork(om.buffer({
@@ -43899,7 +44061,7 @@ var ObservationStep = class {
43899
44061
  }).map((msg) => msg.id);
43900
44062
  inFlightIds = [...new Set(unreadIds)];
43901
44063
  if (messagesToSave.length > 0) {
43902
- for (const msg of messagesToSave) messageList.add(msg, "memory");
44064
+ messageList.add(messagesToSave, "memory");
43903
44065
  try {
43904
44066
  await om.persistMessages(messagesToSave, threadId, resourceId);
43905
44067
  } catch (error) {
@@ -44159,7 +44321,7 @@ var ObservationStep = class {
44159
44321
  const messagesToSeal = messageToSeal ? [messageToSeal] : [];
44160
44322
  this.turn.abortSignal?.throwIfAborted();
44161
44323
  om.sealMessagesForBuffering(messagesToSeal);
44162
- if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation — step-0 seeded response message holds the active id");
44324
+ if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation \u2014 step-0 seeded response message holds the active id");
44163
44325
  else try {
44164
44326
  await this.turn.hooks?.onSyncObservationComplete?.();
44165
44327
  } catch (error) {
@@ -44309,12 +44471,12 @@ var ObservationTurn = class {
44309
44471
  messageList;
44310
44472
  /** The current cached record. Refreshed after mutations (activate/observe/reflect). */
44311
44473
  get record() {
44312
- if (!this._record) throw new Error("Turn not started — call start() first");
44474
+ if (!this._record) throw new Error("Turn not started \u2014 call start() first");
44313
44475
  return this._record;
44314
44476
  }
44315
44477
  /** The context loaded during start(). */
44316
44478
  get context() {
44317
- if (!this._context) throw new Error("Turn not started — call start() first");
44479
+ if (!this._context) throw new Error("Turn not started \u2014 call start() first");
44318
44480
  return this._context;
44319
44481
  }
44320
44482
  /** Whether the turn has been ended and can no longer accept steps. */
@@ -44383,7 +44545,7 @@ var ObservationTurn = class {
44383
44545
  * (its output messages will be saved at the start of the new step's prepare()).
44384
44546
  */
44385
44547
  step(stepNumber) {
44386
- if (!this._started) throw new Error("Turn not started — call start() first");
44548
+ if (!this._started) throw new Error("Turn not started \u2014 call start() first");
44387
44549
  if (this._ended) throw new Error("Turn already ended");
44388
44550
  this._currentStep = new ObservationStep(this, stepNumber);
44389
44551
  return this._currentStep;
@@ -44401,8 +44563,8 @@ var ObservationTurn = class {
44401
44563
  this._ended = true;
44402
44564
  const unsavedInput = messageList.get.input.db();
44403
44565
  const unsavedOutput = messageList.get.response.db();
44404
- const unsavedMessages = [...unsavedInput, ...unsavedOutput];
44405
- if (unsavedMessages.length > 0) await this.om.persistMessages(unsavedMessages, this.threadId, this.resourceId);
44566
+ const unsavedMessages = withMessagesMarkedForResave(messageList, [...unsavedInput, ...unsavedOutput]);
44567
+ if (unsavedMessages.length > 0) await this.om.persistMessages(unsavedMessages, this.threadId, this.resourceId, idsMarkedForResave(messageList, [...unsavedInput, ...unsavedOutput]));
44406
44568
  const asyncObservationEnabled = this.om.buffering.isAsyncObservationEnabled();
44407
44569
  const bufferOnIdle = this.om.getObservationConfig().bufferOnIdle;
44408
44570
  if (!this.abortSignal?.aborted && asyncObservationEnabled && bufferOnIdle) {
@@ -44604,8 +44766,8 @@ When consolidating observations:
44604
44766
  - 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
44605
44767
  - Prefer many short factual lines over prose summaries. Do not replace facts with generalities like "discussed travel plans"
44606
44768
  - Combine related items where it makes sense (e.g., "agent called view tool 5 times on file x")
44607
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44608
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
44769
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44770
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
44609
44771
  - Condense the wording of older observations more than recent ones, but keep their facts
44610
44772
 
44611
44773
  CRITICAL: USER ASSERTIONS vs QUESTIONS
@@ -44627,23 +44789,23 @@ When observations contain <thread id="..."> sections:
44627
44789
  Example input:
44628
44790
  <thread id="thread-1">
44629
44791
  Date: Dec 4, 2025
44630
- * 🔴 (14:30) User prefers TypeScript
44631
- * 🟡 (14:35) Working on auth feature
44792
+ * \u{1F534} (14:30) User prefers TypeScript
44793
+ * \u{1F7E1} (14:35) Working on auth feature
44632
44794
  </thread>
44633
44795
  <thread id="thread-2">
44634
44796
  Date: Dec 4, 2025
44635
- * 🔴 (15:00) User prefers TypeScript
44636
- * 🟡 (15:05) Debugging API endpoint
44797
+ * \u{1F534} (15:00) User prefers TypeScript
44798
+ * \u{1F7E1} (15:05) Debugging API endpoint
44637
44799
  </thread>
44638
44800
 
44639
44801
  Example output (consolidated):
44640
44802
  Date: Dec 4, 2025
44641
- * 🔴 (14:30) User prefers TypeScript
44803
+ * \u{1F534} (14:30) User prefers TypeScript
44642
44804
  <thread id="thread-1">
44643
- * 🟡 (14:35) Working on auth feature
44805
+ * \u{1F7E1} (14:35) Working on auth feature
44644
44806
  </thread>
44645
44807
  <thread id="thread-2">
44646
- * 🟡 (15:05) Debugging API endpoint
44808
+ * \u{1F7E1} (15:05) Debugging API endpoint
44647
44809
  </thread>
44648
44810
 
44649
44811
  === OUTPUT FORMAT ===
@@ -44674,8 +44836,8 @@ Please re-process with slightly more compression:
44674
44836
  - Memory is getting long - use a more condensed style throughout
44675
44837
  - Combine related items more aggressively but do not lose important specific details of names, places, events, and people
44676
44838
  - 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
44677
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44678
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
44839
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44840
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
44679
44841
 
44680
44842
  Aim for a 8/10 detail level.
44681
44843
  `,
@@ -44691,8 +44853,8 @@ Please re-process with much more aggressive compression:
44691
44853
  - Combine related items aggressively but do not lose important specific details of names, places, events, and people
44692
44854
  - 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
44693
44855
  - If the same file or module is mentioned across many observations, merge into one entry covering the full arc
44694
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44695
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
44856
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44857
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
44696
44858
  - Remove redundant information and merge overlapping observations
44697
44859
 
44698
44860
  Aim for a 6/10 detail level.
@@ -44703,14 +44865,14 @@ Aim for a 6/10 detail level.
44703
44865
  Your previous reflections have failed to compress sufficiently after multiple attempts.
44704
44866
 
44705
44867
  Please re-process with maximum compression:
44706
- - Summarize the oldest observations (first 50-70%) into brief high-level paragraphs — only key facts, decisions, and outcomes
44868
+ - Summarize the oldest observations (first 50-70%) into brief high-level paragraphs \u2014 only key facts, decisions, and outcomes
44707
44869
  - For the most recent observations (last 30-50%), retain important details but still use a condensed style
44708
- - Ruthlessly merge related observations — if 10 observations are about the same topic, combine into 1-2 lines
44709
- - Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries — drop individual steps entirely
44710
- - Drop procedural details (tool calls, retries, intermediate steps) — keep only final outcomes
44870
+ - Ruthlessly merge related observations \u2014 if 10 observations are about the same topic, combine into 1-2 lines
44871
+ - Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries \u2014 drop individual steps entirely
44872
+ - Drop procedural details (tool calls, retries, intermediate steps) \u2014 keep only final outcomes
44711
44873
  - Drop observations that are no longer relevant or have been superseded by newer information
44712
- - Preserve ✅ completion markers — they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44713
- - Preserve the concrete resolved outcome captured by ✅ markers so the assistant knows what exactly is done
44874
+ - Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
44875
+ - Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
44714
44876
  - Preserve: names, dates, decisions, errors, user preferences, and architectural choices
44715
44877
 
44716
44878
  Aim for a 4/10 detail level.
@@ -44721,14 +44883,14 @@ Aim for a 4/10 detail level.
44721
44883
  Multiple compression attempts have failed. The content may already be dense from a prior reflection.
44722
44884
 
44723
44885
  You MUST dramatically reduce the number of observations while keeping the standard observation format (date groups with bullet points and priority emojis):
44724
- - 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")
44725
- - Never preserve individual tool calls (viewed file X, searched for Y, ran build) — only preserve what was discovered or accomplished
44886
+ - 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")
44887
+ - Never preserve individual tool calls (viewed file X, searched for Y, ran build) \u2014 only preserve what was discovered or accomplished
44726
44888
  - Consolidate many related observations into single, more generic observations
44727
44889
  - Merge all same-day date groups into at most 2-3 date groups per day
44728
44890
  - For older content, each topic or task should be at most 1-2 observations capturing the key outcome
44729
44891
  - For recent content, retain more detail but still merge related items aggressively
44730
44892
  - If multiple observations describe incremental progress on the same task, keep only the final state
44731
- - Preserve ✅ completion markers and their outcomes but merge related completions into fewer lines
44893
+ - Preserve \u2705 completion markers and their outcomes but merge related completions into fewer lines
44732
44894
  - Preserve: user preferences, key decisions, architectural choices, and unresolved issues
44733
44895
 
44734
44896
  Aim for a 2/10 detail level. Fewer, more generic observations are better than many specific ones that exceed the budget.
@@ -45151,7 +45313,7 @@ var ReflectorRunner = class {
45151
45313
  operationType: "reflection",
45152
45314
  startedAt: streamContext.startedAt,
45153
45315
  tokensAttempted: originalTokens,
45154
- error: `Did not compress below threshold (${originalTokens} → ${reflectedTokens}, target: ${targetThreshold}), retrying at level ${currentLevel + 1}`,
45316
+ error: `Did not compress below threshold (${originalTokens} \u2192 ${reflectedTokens}, target: ${targetThreshold}), retrying at level ${currentLevel + 1}`,
45155
45317
  retrying: true,
45156
45318
  recordId: streamContext.recordId,
45157
45319
  threadId: streamContext.threadId
@@ -45181,7 +45343,7 @@ var ReflectorRunner = class {
45181
45343
  }
45182
45344
  currentLevel = Math.min(currentLevel + 1, maxLevel);
45183
45345
  }
45184
- 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`);
45346
+ 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`);
45185
45347
  const structuredExtraction = await extractStructuredValues({
45186
45348
  agent,
45187
45349
  source: "reflector",
@@ -45322,7 +45484,7 @@ var ReflectorRunner = class {
45322
45484
  const reflectedObservationLineCount = linesToReflect;
45323
45485
  const sliceTokenEstimate = Math.round(avgTokensPerLine * linesToReflect);
45324
45486
  const compressionTarget = Math.round(sliceTokenEstimate * .75);
45325
- omDebug(`[OM:reflect] doAsyncBufferedReflection: slicing observations for reflection — totalLines=${totalLines}, avgTokPerLine=${avgTokensPerLine.toFixed(1)}, activationPointTokens=${activationPointTokens}, linesToReflect=${linesToReflect}/${totalLines}, sliceTokenEstimate=${sliceTokenEstimate}, compressionTarget=${compressionTarget}`);
45487
+ omDebug(`[OM:reflect] doAsyncBufferedReflection: slicing observations for reflection \u2014 totalLines=${totalLines}, avgTokPerLine=${avgTokensPerLine.toFixed(1)}, activationPointTokens=${activationPointTokens}, linesToReflect=${linesToReflect}/${totalLines}, sliceTokenEstimate=${sliceTokenEstimate}, compressionTarget=${compressionTarget}`);
45326
45488
  omDebug(`[OM:reflect] doAsyncBufferedReflection: starting reflector call, recordId=${currentRecord.id}, observationTokens=${sliceTokenEstimate}, compressionTarget=${compressionTarget} (inputTokens), activeObsLength=${activeObservations.length}, reflectedLineCount=${reflectedObservationLineCount}`);
45327
45489
  if (writer) {
45328
45490
  const startMarker = createBufferingStartMarker({
@@ -45494,7 +45656,7 @@ var ReflectorRunner = class {
45494
45656
  const unreflectedTailTokens = unreflectedContent ? this.tokenCounter.countObservations(unreflectedContent) : 0;
45495
45657
  const bufferedReflectionTokens = freshRecord.bufferedReflectionTokens ?? 0;
45496
45658
  if (unreflectedTailTokens < bufferedReflectionTokens) {
45497
- omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation — unreflectedTailTokens=${unreflectedTailTokens} < bufferedReflectionTokens=${bufferedReflectionTokens}; keeping buffer for threshold activation`);
45659
+ omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation \u2014 unreflectedTailTokens=${unreflectedTailTokens} < bufferedReflectionTokens=${bufferedReflectionTokens}; keeping buffer for threshold activation`);
45498
45660
  return {
45499
45661
  status: "suppressed",
45500
45662
  reason: "composition"
@@ -45505,7 +45667,7 @@ var ReflectorRunner = class {
45505
45667
  const regularActivationTarget = reflectThreshold * (1 - bufferActivation);
45506
45668
  const minCombinedTokens = Math.round(regularActivationTarget * EARLY_ACTIVATION_SIZE_FLOOR_RATIO);
45507
45669
  if (combinedTokenCount < minCombinedTokens) {
45508
- 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`);
45670
+ 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`);
45509
45671
  return {
45510
45672
  status: "suppressed",
45511
45673
  reason: "size"
@@ -45634,7 +45796,7 @@ var ReflectorRunner = class {
45634
45796
  omDebug(`[OM:reflect] isReflecting=true and active in this process, skipping`);
45635
45797
  return;
45636
45798
  }
45637
- omDebug(`[OM:reflect] isReflecting=true but NOT active in this process — stale flag from dead process, clearing`);
45799
+ omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
45638
45800
  await this.storage.setReflectingFlag(record.id, false);
45639
45801
  }
45640
45802
  if (this.buffering.isAsyncReflectionEnabled()) {
@@ -45648,15 +45810,15 @@ var ReflectorRunner = class {
45648
45810
  else {
45649
45811
  const activationPoint = reflectThreshold * this.reflectionConfig.bufferActivation;
45650
45812
  if (observationTokens < activationPoint) {
45651
- omDebug(`[OM:reflect] skipping async reflection — observationTokens (${observationTokens}) below activation point (${activationPoint}), triggered by ${activationTriggeredBy}`);
45813
+ omDebug(`[OM:reflect] skipping async reflection \u2014 observationTokens (${observationTokens}) below activation point (${activationPoint}), triggered by ${activationTriggeredBy}`);
45652
45814
  return;
45653
45815
  }
45654
45816
  const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
45655
45817
  if (this.buffering.isAsyncBufferingInProgress(bufferKey) || BufferingCoordinator.lastBufferedBoundary.has(bufferKey)) {
45656
- omDebug(`[OM:reflect] skipping async reflection — reflection buffer already active or present for ${bufferKey}`);
45818
+ omDebug(`[OM:reflect] skipping async reflection \u2014 reflection buffer already active or present for ${bufferKey}`);
45657
45819
  return;
45658
45820
  }
45659
- omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) — starting background reflection`);
45821
+ omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) \u2014 starting background reflection`);
45660
45822
  this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
45661
45823
  return;
45662
45824
  }
@@ -45664,7 +45826,7 @@ var ReflectorRunner = class {
45664
45826
  if (activationTriggeredBy === "threshold") {
45665
45827
  const suppressedAtTokens = this.syncReflectionSuppression.get(lockKey);
45666
45828
  if (suppressedAtTokens !== void 0 && observationTokens === suppressedAtTokens) {
45667
- omDebug(`[OM:reflect] skipping sync reflection — observations unchanged at ${observationTokens} tokens since the last unproductive attempt; retrying once they change`);
45829
+ omDebug(`[OM:reflect] skipping sync reflection \u2014 observations unchanged at ${observationTokens} tokens since the last unproductive attempt; retrying once they change`);
45668
45830
  return;
45669
45831
  }
45670
45832
  }
@@ -46505,7 +46667,7 @@ var ObservationalMemory = class ObservationalMemory {
46505
46667
  const asyncBufferingDisabled = config.observation?.bufferTokens === false || config.scope === "resource" && !userExplicitlyConfiguredAsync;
46506
46668
  if (isSharedBudget && !asyncBufferingDisabled) {
46507
46669
  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).");
46508
- 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.");
46670
+ 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.");
46509
46671
  }
46510
46672
  const observationActivateAfterIdle = config.observation?.activateAfterIdle ?? config.activateAfterIdle;
46511
46673
  const observationActivateAfterIdlePath = config.observation?.activateAfterIdle !== void 0 ? "observation.activateAfterIdle" : "activateAfterIdle";
@@ -46602,7 +46764,7 @@ var ObservationalMemory = class ObservationalMemory {
46602
46764
  hasWarnedResourceScopeDeprecation = true;
46603
46765
  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");
46604
46766
  }
46605
- 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}`);
46767
+ 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}`);
46606
46768
  }
46607
46769
  __registerMastra(mastra) {
46608
46770
  this.mastra = mastra;
@@ -46883,7 +47045,7 @@ var ObservationalMemory = class ObservationalMemory {
46883
47045
  threadId: null,
46884
47046
  resourceId: resourceId ?? threadId
46885
47047
  };
46886
- 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.");
47048
+ 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.");
46887
47049
  return {
46888
47050
  threadId,
46889
47051
  resourceId: resourceId ?? threadId
@@ -47194,7 +47356,7 @@ var ObservationalMemory = class ObservationalMemory {
47194
47356
  const isImportant = new Array(totalCount);
47195
47357
  for (let i = 0; i < totalCount; i++) {
47196
47358
  lineTokens[i] = this.tokenCounter.countString(lines[i]);
47197
- isImportant[i] = lines[i].includes("🔴") || lines[i].includes("✅");
47359
+ isImportant[i] = lines[i].includes("\u{1F534}") || lines[i].includes("\u2705");
47198
47360
  }
47199
47361
  const suffixTokens = new Array(totalCount + 1);
47200
47362
  suffixTokens[totalCount] = 0;
@@ -47306,18 +47468,86 @@ var ObservationalMemory = class ObservationalMemory {
47306
47468
  * to detect already-persisted messages, avoiding redundant DB operations.
47307
47469
  *
47308
47470
  * Messages with observation markers are always saved (upserted) even if sealed,
47309
- * because the markers need to be persisted to storage.
47471
+ * because the markers need to be persisted to storage. A stored message in `resaveIds` gained token
47472
+ * counts after it was stored, whether or not it is sealed: only those counts are copied onto the stored
47473
+ * copy, see {@link persistTokenEstimatesOntoStored}; one with no stored row was deleted during the turn and stays deleted. Ids in `resaveIds` must not be this turn's own
47474
+ * input or output, which are saved whole.
47310
47475
  */
47311
- async persistMessages(messagesToSave, threadId, resourceId) {
47476
+ async persistMessages(messagesToSave, threadId, resourceId, resaveIds) {
47312
47477
  const filteredMessages = [];
47313
- for (const msg of messagesToSave) if (!!(msg.content?.metadata)?.mastra?.sealed) {
47314
- if (findLastCompletedObservationBoundary(msg) !== -1) filteredMessages.push(msg);
47315
- } else filteredMessages.push(msg);
47478
+ const storedWithNewCounts = [];
47479
+ for (const msg of messagesToSave) {
47480
+ if (!!(msg.content?.metadata)?.mastra?.sealed && findLastCompletedObservationBoundary(msg) === -1 && !resaveIds?.has(msg.id)) continue;
47481
+ if (resaveIds?.has(msg.id) && findLastCompletedObservationBoundary(msg) === -1) storedWithNewCounts.push(msg);
47482
+ else filteredMessages.push(msg);
47483
+ }
47316
47484
  if (filteredMessages.length > 0) await this.messageHistory.persistMessages({
47317
47485
  messages: filteredMessages,
47318
47486
  threadId,
47319
47487
  resourceId
47320
47488
  });
47489
+ try {
47490
+ await this.persistTokenEstimatesOntoStored(storedWithNewCounts);
47491
+ } catch (error) {
47492
+ omError("[OM] Failed to save token counts for stored messages", error);
47493
+ }
47494
+ }
47495
+ /**
47496
+ * Copy the token counts of `messages` onto their stored copies. A stored copy can hold
47497
+ * parts the in-memory one lacks (markers written straight to storage), so it is patched
47498
+ * instead of saved whole. Each count goes to the first stored part whose content matches the counted
47499
+ * part, so a part that changed in storage keeps no count and is counted again on read.
47500
+ */
47501
+ async persistTokenEstimatesOntoStored(messages) {
47502
+ if (messages.length === 0) return;
47503
+ const contentOf = (part) => {
47504
+ const { tokenEstimate: _tokenEstimate, ...mastra } = part.providerMetadata?.mastra ?? {};
47505
+ return JSON.stringify({
47506
+ ...part,
47507
+ providerMetadata: {
47508
+ ...part.providerMetadata,
47509
+ mastra
47510
+ }
47511
+ });
47512
+ };
47513
+ const live = new Map(messages.map((message) => [message.id, message]));
47514
+ const { messages: stored } = await this.storage.listMessagesById({ messageIds: [...live.keys()] });
47515
+ const updates = [];
47516
+ for (const row of stored) {
47517
+ const counts = /* @__PURE__ */ new Map();
47518
+ for (const part of live.get(row.id)?.content.parts ?? []) {
47519
+ const tokenEstimate = part.providerMetadata?.mastra?.tokenEstimate;
47520
+ if (!tokenEstimate) continue;
47521
+ const key = contentOf(part);
47522
+ counts.set(key, [...counts.get(key) ?? [], tokenEstimate]);
47523
+ }
47524
+ if (counts.size === 0) continue;
47525
+ let changed = false;
47526
+ const parts = row.content.parts.map((part) => {
47527
+ const tokenEstimate = counts.get(contentOf(part))?.shift();
47528
+ if (!tokenEstimate) return part;
47529
+ changed = true;
47530
+ const providerMetadata = part.providerMetadata ?? {};
47531
+ return {
47532
+ ...part,
47533
+ providerMetadata: {
47534
+ ...providerMetadata,
47535
+ mastra: {
47536
+ ...providerMetadata.mastra,
47537
+ tokenEstimate
47538
+ }
47539
+ }
47540
+ };
47541
+ });
47542
+ if (changed) updates.push({
47543
+ id: row.id,
47544
+ content: {
47545
+ ...row.content,
47546
+ parts
47547
+ }
47548
+ });
47549
+ }
47550
+ if (updates.length > 0) await this.storage.updateMessages({ messages: updates });
47321
47551
  }
47322
47552
  /**
47323
47553
  * Load messages from storage that haven't been observed yet.
@@ -47527,7 +47757,7 @@ ${formattedMessages}
47527
47757
  resourceId: freshRecord.resourceId ?? void 0
47528
47758
  });
47529
47759
  } catch (err) {
47530
- omError("[OM] Failed to persist sealed messages before buffering — skipping observation cycle", err);
47760
+ omError("[OM] Failed to persist sealed messages before buffering \u2014 skipping observation cycle", err);
47531
47761
  return;
47532
47762
  }
47533
47763
  const cycleId = `buffer-obs-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
@@ -48677,7 +48907,7 @@ ${formattedMessages}
48677
48907
  usage: void 0
48678
48908
  };
48679
48909
  }
48680
- omDebug(`[OM:reflect] isReflecting=true but NOT active in this process — stale flag from dead process, clearing`);
48910
+ omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
48681
48911
  await this.storage.setReflectingFlag(record.id, false);
48682
48912
  }
48683
48913
  await this.storage.setReflectingFlag(record.id, true);
@@ -48911,7 +49141,7 @@ ${formattedMessages}
48911
49141
  };
48912
49142
  const TEMPORAL_GAP_REMINDER_TYPE = "temporal-gap";
48913
49143
  function getTemporalGapReminderText(gapText, timestamp) {
48914
- return `${gapText} — ${formatTemporalTimestamp(new Date(timestamp))}`;
49144
+ return `${gapText} \u2014 ${formatTemporalTimestamp(new Date(timestamp))}`;
48915
49145
  }
48916
49146
  function getTemporalGapReminderMetadata(message, gapText, gapMs, timestamp) {
48917
49147
  const formattedTimestamp = formatTemporalTimestamp(new Date(timestamp));
@@ -49118,11 +49348,12 @@ var ObservationalMemoryProcessor = class {
49118
49348
  state.__omTurn = void 0;
49119
49349
  if (!activeTurn || activeTurn.ended) return;
49120
49350
  const terminalList = messageList ?? activeTurn.messageList;
49121
- const unsavedMessages = [...terminalList.get.input.db(), ...terminalList.get.response.db()];
49351
+ const ownMessages = [...terminalList.get.input.db(), ...terminalList.get.response.db()];
49352
+ const unsavedMessages = withMessagesMarkedForResave(terminalList, ownMessages);
49122
49353
  try {
49123
49354
  await activeTurn.end(terminalList);
49124
49355
  } catch (error) {
49125
- if (unsavedMessages.length > 0) await this.engine.persistMessages(unsavedMessages, activeTurn.threadId, activeTurn.resourceId).catch(() => {});
49356
+ if (unsavedMessages.length > 0) await this.engine.persistMessages(unsavedMessages, activeTurn.threadId, activeTurn.resourceId, idsMarkedForResave(terminalList, ownMessages)).catch(() => {});
49126
49357
  throw error;
49127
49358
  }
49128
49359
  }
@@ -49132,14 +49363,14 @@ var ObservationalMemoryProcessor = class {
49132
49363
  omDebug(`[OM:processInputStep:ENTER] step=${stepNumber}, hasMastraMemory=${!!requestContext?.get("MastraMemory")}, hasMemoryInfo=${!!messageList?.serialize()?.memoryInfo?.threadId}`);
49133
49364
  const context = this.engine.getThreadContext(requestContext, messageList);
49134
49365
  if (!context) {
49135
- omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null — returning early`);
49366
+ omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null \u2014 returning early`);
49136
49367
  return messageList;
49137
49368
  }
49138
49369
  const gatewayMemoryManaged = await isGatewayMemoryManaged(model);
49139
49370
  state[GATEWAY_STATE_KEY] = gatewayMemoryManaged;
49140
49371
  if (gatewayMemoryManaged) {
49141
49372
  await this.endActiveTurn(state);
49142
- omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory — skipping local processing`);
49373
+ omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory \u2014 skipping local processing`);
49143
49374
  return messageList;
49144
49375
  }
49145
49376
  const { threadId, resourceId } = context;
@@ -49264,6 +49495,7 @@ var ObservationalMemoryProcessor = class {
49264
49495
  this.turn.responseMessageId = responseMessageId;
49265
49496
  {
49266
49497
  const step = this.turn.step(stepNumber);
49498
+ const resaveCounted = resaveCountedMessagesFor(messageList, threadId);
49267
49499
  let ctx;
49268
49500
  try {
49269
49501
  ctx = await step.prepare();
@@ -49298,6 +49530,7 @@ var ObservationalMemoryProcessor = class {
49298
49530
  threadId,
49299
49531
  resourceId
49300
49532
  });
49533
+ resaveCounted();
49301
49534
  const finalTotalPending = ctx.status.pendingTokens;
49302
49535
  try {
49303
49536
  await runOMCommit(this.engine.buffering.getLockKey(threadId, resourceId), () => this.engine.getStorage().setPendingMessageTokens(turnRecord.id, finalTotalPending), { abortSignal });
@@ -49337,6 +49570,7 @@ var ObservationalMemoryProcessor = class {
49337
49570
  return this.engine.getTokenCounter().runWithModelContext(state.__omActorModelContext, async () => {
49338
49571
  if (parseMemoryRequestContext(requestContext)?.memoryConfig?.readOnly) return messageList;
49339
49572
  const persistenceMessageList = messageList.cloneForPersistence();
49573
+ this.engine.getTokenCounter().countMessages(persistenceMessageList.get.response.db());
49340
49574
  const turn = asLiveTurn(state.__omTurn) ?? this.turn;
49341
49575
  const liveTurn = turn && !turn.ended ? turn : void 0;
49342
49576
  if (liveTurn) await liveTurn.end(persistenceMessageList);
@@ -49344,8 +49578,9 @@ var ObservationalMemoryProcessor = class {
49344
49578
  state.__omTurn = void 0;
49345
49579
  if (!liveTurn) {
49346
49580
  const newOutput = persistenceMessageList.get.response.db();
49347
- const messagesToSave = [...persistenceMessageList.get.input.db(), ...newOutput];
49348
- if (messagesToSave.length > 0 && context.threadId) await this.engine.persistMessages(messagesToSave, context.threadId, context.resourceId);
49581
+ const ownMessages = [...persistenceMessageList.get.input.db(), ...newOutput];
49582
+ const messagesToSave = withMessagesMarkedForResave(persistenceMessageList, ownMessages);
49583
+ if (messagesToSave.length > 0 && context.threadId) await this.engine.persistMessages(messagesToSave, context.threadId, context.resourceId, idsMarkedForResave(persistenceMessageList, ownMessages));
49349
49584
  }
49350
49585
  return messageList;
49351
49586
  });
@@ -49360,7 +49595,7 @@ var ObservationalMemoryProcessor = class {
49360
49595
  if (!context) return;
49361
49596
  if (parseMemoryRequestContext(requestContext)?.memoryConfig?.readOnly) return;
49362
49597
  state[CONTEXT_OVERFLOW_STEP_KEY] = stepNumber;
49363
- omDebug(`[OM:processAPIError] context overflow at step ${stepNumber} — observing pending messages`);
49598
+ omDebug(`[OM:processAPIError] context overflow at step ${stepNumber} \u2014 observing pending messages`);
49364
49599
  const { threadId, resourceId } = context;
49365
49600
  await this.engine.waitForBuffering(threadId, resourceId, void 0, args.abortSignal);
49366
49601
  const messages = getObservableMessages(messageList);
@@ -51959,7 +52194,7 @@ var import_ignore = /* @__PURE__ */ __toESM$1((/* @__PURE__ */ __commonJSMin$1((
51959
52194
  const SPACE = " ";
51960
52195
  const ESCAPE = "\\";
51961
52196
  const REGEX_LITERAL_SPECIAL = /[.*+?()[\]{}^$|\\/]/;
51962
- const BOM = "";
52197
+ const BOM = "\uFEFF";
51963
52198
  const REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
51964
52199
  const REGEX_ANCHORED_GLOBSTAR = /^\/\*{2,}$/;
51965
52200
  const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
@@ -52056,8 +52291,8 @@ var import_ignore = /* @__PURE__ */ __toESM$1((/* @__PURE__ */ __commonJSMin$1((
52056
52291
  const NEVER_MATCH = "[]";
52057
52292
  const PLACEHOLDER = "\0";
52058
52293
  const REGEX_RESTORE_PLACEHOLDER = new RegExp(`${PLACEHOLDER}(\\d+)${PLACEHOLDER}`, "g");
52059
- const TRAILING_WILDCARD = "";
52060
- const TRAILING_DOUBLESTAR = "";
52294
+ const TRAILING_WILDCARD = "\uE000";
52295
+ const TRAILING_DOUBLESTAR = "\uE001";
52061
52296
  const isReserved = (char) => char === PLACEHOLDER || char === TRAILING_WILDCARD || char === TRAILING_DOUBLESTAR;
52062
52297
  const extractBrackets = (pattern) => {
52063
52298
  const sources = [];
@@ -52827,7 +53062,7 @@ async function logGitState(targetPath, label) {
52827
53062
  const gitStatusResult = await git(targetPath, "status", "--porcelain");
52828
53063
  const gitLogResult = await git(targetPath, "log", "--oneline", "-3");
52829
53064
  const gitCountResult = await git(targetPath, "rev-list", "--count", "HEAD");
52830
- console.info(`📊 Git state ${label}:`);
53065
+ console.info(`\u{1F4CA} Git state ${label}:`);
52831
53066
  console.info("Status:", gitStatusResult.stdout.trim() || "Clean working directory");
52832
53067
  console.info("Recent commits:", gitLogResult.stdout.trim());
52833
53068
  console.info("Total commits:", gitCountResult.stdout.trim());
@@ -52919,9 +53154,9 @@ async function gitCheckoutBranch(branchName, targetPath) {
52919
53154
  async function backupAndReplaceFile(sourceFile, targetFile) {
52920
53155
  const backupFile = `${targetFile}.backup-${Date.now()}`;
52921
53156
  await copyFile(targetFile, backupFile);
52922
- console.info(`📦 Created backup: ${basename(backupFile)}`);
53157
+ console.info(`\u{1F4E6} Created backup: ${basename(backupFile)}`);
52923
53158
  await copyFile(sourceFile, targetFile);
52924
- console.info(`🔄 Replaced file with template version (backup created)`);
53159
+ console.info(`\u{1F504} Replaced file with template version (backup created)`);
52925
53160
  }
52926
53161
  async function renameAndCopyFile(sourceFile, targetFile) {
52927
53162
  let counter = 1;
@@ -52935,7 +53170,7 @@ async function renameAndCopyFile(sourceFile, targetFile) {
52935
53170
  counter++;
52936
53171
  }
52937
53172
  await copyFile(sourceFile, uniqueTargetFile);
52938
- console.info(`📝 Copied with unique name: ${basename(uniqueTargetFile)}`);
53173
+ console.info(`\u{1F4DD} Copied with unique name: ${basename(uniqueTargetFile)}`);
52939
53174
  return uniqueTargetFile;
52940
53175
  }
52941
53176
  const isValidMastraLanguageModel = (model) => {
@@ -52973,7 +53208,7 @@ const mergeGitignoreFiles = (targetContent, templateContent, templateSlug) => {
52973
53208
  const isNegation = normalized.startsWith("!");
52974
53209
  const basePath = isNegation ? normalized.slice(1) : normalized;
52975
53210
  if (!(isNegation ? existingEntries.has(basePath) : existingEntries.has("!" + basePath))) newEntries.push(trimmed);
52976
- else console.info(`⚠ Skipping conflicting .gitignore rule: ${trimmed} (conflicts with existing rule)`);
53211
+ else console.info(`\u26A0 Skipping conflicting .gitignore rule: ${trimmed} (conflicts with existing rule)`);
52977
53212
  }
52978
53213
  }
52979
53214
  }
@@ -53003,7 +53238,7 @@ const mergeEnvFiles = (targetContent, templateVariables, templateSlug) => {
53003
53238
  key,
53004
53239
  value
53005
53240
  });
53006
- else console.info(`⚠ Skipping existing environment variable: ${key} (already exists in .env)`);
53241
+ else console.info(`\u26A0 Skipping existing environment variable: ${key} (already exists in .env)`);
53007
53242
  if (newVars.length === 0) return targetContent;
53008
53243
  const result = [...targetLines];
53009
53244
  const lastLine = result[result.length - 1];
@@ -53058,7 +53293,7 @@ const createModelInstance = async (provider, modelId, version = "v2") => {
53058
53293
  try {
53059
53294
  const providerFn = version === `v1` ? { v1: {
53060
53295
  openai: async () => {
53061
- const { openai } = await import("./dist-Bn0zFASI.js");
53296
+ const { openai } = await import("./dist-BWVxgpEw.js");
53062
53297
  return openai(modelId);
53063
53298
  },
53064
53299
  anthropic: async () => {
@@ -53127,25 +53362,25 @@ IF NO PROJECT EXISTS, USE THE MANAGEPROJECT TOOL TO CREATE A NEW PROJECT
53127
53362
 
53128
53363
  DO NOT INCLUDE TODOS IN THE CODE, UNLESS SPECIFICALLY ASKED TO DO SO, CREATE REAL WORLD CODE
53129
53364
 
53130
- ### 1. 🔍 **UNDERSTAND** (Information Gathering)
53365
+ ### 1. \u{1F50D} **UNDERSTAND** (Information Gathering)
53131
53366
  - **Explore Mastra Docs**: Use docs tools to understand relevant Mastra patterns and APIs
53132
53367
  - **Analyze Project**: Use file exploration to understand existing codebase structure
53133
53368
  - **Web Research**: Search for packages, examples, or solutions when docs are insufficient
53134
53369
  - **Clarify Requirements**: Ask targeted questions only when critical information is missing
53135
53370
 
53136
- ### 2. 📋 **PLAN** (Strategy & Design)
53371
+ ### 2. \u{1F4CB} **PLAN** (Strategy & Design)
53137
53372
  - **Architecture**: Design using Mastra conventions (agents, tools, workflows, memory)
53138
53373
  - **Dependencies**: Identify required packages and Mastra components
53139
53374
  - **Integration**: Plan how to integrate with existing project structure
53140
53375
  - **Validation**: Define how to test and verify the implementation
53141
53376
 
53142
- ### 3. 🛠️ **BUILD** (Implementation)
53377
+ ### 3. \u{1F6E0}\uFE0F **BUILD** (Implementation)
53143
53378
  - **Install First**: Use \`manageProject\` tool to install required packages
53144
53379
  - **Follow Patterns**: Implement using established Mastra conventions
53145
53380
  - **Real Code Only**: Build actual working functionality, never mock implementations
53146
53381
  - **Environment Setup**: Create proper .env configuration and documentation
53147
53382
 
53148
- ### 4. ✅ **VALIDATE** (Quality Assurance)
53383
+ ### 4. \u2705 **VALIDATE** (Quality Assurance)
53149
53384
  - **Code Validation**: Run \`validateCode\` with types and lint checks
53150
53385
  - **Testing**: Execute tests if available
53151
53386
  - **Server Testing**: Use \`manageServer\` and \`httpRequest\` for API validation
@@ -53242,23 +53477,23 @@ DO NOT INCLUDE TODOS IN THE CODE, UNLESS SPECIFICALLY ASKED TO DO SO, CREATE REA
53242
53477
  ## Output Requirements
53243
53478
 
53244
53479
  ### Code Quality
53245
- - ✅ TypeScript compilation passes
53246
- - ✅ ESLint validation passes
53247
- - ✅ Proper error handling implemented
53248
- - ✅ Environment variables configured
53249
- - ✅ Tests included when appropriate
53480
+ - \u2705 TypeScript compilation passes
53481
+ - \u2705 ESLint validation passes
53482
+ - \u2705 Proper error handling implemented
53483
+ - \u2705 Environment variables configured
53484
+ - \u2705 Tests included when appropriate
53250
53485
 
53251
53486
  ### Documentation
53252
- - ✅ Clear setup instructions
53253
- - ✅ Environment variable documentation
53254
- - ✅ Usage examples provided
53255
- - ✅ API documentation for custom tools
53487
+ - \u2705 Clear setup instructions
53488
+ - \u2705 Environment variable documentation
53489
+ - \u2705 Usage examples provided
53490
+ - \u2705 API documentation for custom tools
53256
53491
 
53257
53492
  ### Integration
53258
- - ✅ Follows Mastra conventions
53259
- - ✅ Integrates with existing project
53260
- - ✅ Proper imports and exports
53261
- - ✅ Compatible with Mastra ecosystem
53493
+ - \u2705 Follows Mastra conventions
53494
+ - \u2705 Integrates with existing project
53495
+ - \u2705 Proper imports and exports
53496
+ - \u2705 Compatible with Mastra ecosystem
53262
53497
 
53263
53498
  ## Project Context
53264
53499
 
@@ -53805,7 +54040,7 @@ export const mastra = new Mastra({
53805
54040
  }),
53806
54041
  validateCode: createTool({
53807
54042
  id: "validate-code",
53808
- description: "Validates code using a fast hybrid approach: syntax → semantic → lint. RECOMMENDED: Always provide specific files for optimal performance and accuracy.",
54043
+ description: "Validates code using a fast hybrid approach: syntax \u2192 semantic \u2192 lint. RECOMMENDED: Always provide specific files for optimal performance and accuracy.",
53809
54044
  inputSchema: z$2.object({
53810
54045
  projectPath: z$2.string().optional().describe("Path to the project to validate (defaults to current project)"),
53811
54046
  validationType: z$2.array(z$2.enum([
@@ -53815,7 +54050,7 @@ export const mastra = new Mastra({
53815
54050
  "tests",
53816
54051
  "build"
53817
54052
  ])).describe("Types of validation to perform. Recommended: [\"types\", \"lint\"] for code quality"),
53818
- 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.")
54053
+ 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.")
53819
54054
  }),
53820
54055
  outputSchema: z$2.object({
53821
54056
  valid: z$2.boolean(),
@@ -55698,8 +55933,8 @@ For each Mastra project directory you analyze:
55698
55933
  IMPORTANT - Naming Consistency Rules:
55699
55934
  - For ALL unit types (including 'other'), the 'name' field should be the filename WITHOUT extension
55700
55935
  - For structured units (agents, workflows, tools, etc.), prefer the actual export name if clearly identifiable
55701
- - use the base filename without extension for the id (e.g., 'util.ts' → name: 'util')
55702
- - use the relative path from the template root for the file (e.g., 'src/mastra/lib/util.ts' → file: 'src/mastra/lib/util.ts')
55936
+ - use the base filename without extension for the id (e.g., 'util.ts' \u2192 name: 'util')
55937
+ - 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')
55703
55938
 
55704
55939
  Return the actual exported names of the units, as well as the file names.`,
55705
55940
  name: "Mastra Project Discoverer",
@@ -56055,7 +56290,7 @@ const programmaticFileCopyStep = createStep({
56055
56290
  sourceFile: unit.file,
56056
56291
  targetFile: `${targetDir}/${convertedFileName}`
56057
56292
  });
56058
- console.info(`⏭️ Skipped ${unit.kind} "${unit.id}": file already exists`);
56293
+ console.info(`\u23ED\uFE0F Skipped ${unit.kind} "${unit.id}": file already exists`);
56059
56294
  continue;
56060
56295
  case "backup-and-replace": try {
56061
56296
  await backupAndReplaceFile(sourceFile, targetFile);
@@ -56067,7 +56302,7 @@ const programmaticFileCopyStep = createStep({
56067
56302
  id: unit.id
56068
56303
  }
56069
56304
  });
56070
- console.info(`🔄 Replaced ${unit.kind} "${unit.id}": ${unit.file} → ${convertedFileName} (backup created)`);
56305
+ console.info(`\u{1F504} Replaced ${unit.kind} "${unit.id}": ${unit.file} \u2192 ${convertedFileName} (backup created)`);
56071
56306
  continue;
56072
56307
  } catch (backupError) {
56073
56308
  conflicts.push({
@@ -56091,7 +56326,7 @@ const programmaticFileCopyStep = createStep({
56091
56326
  id: unit.id
56092
56327
  }
56093
56328
  });
56094
- console.info(`📝 Renamed ${unit.kind} "${unit.id}": ${unit.file} → ${basename(uniqueTargetFile)}`);
56329
+ console.info(`\u{1F4DD} Renamed ${unit.kind} "${unit.id}": ${unit.file} \u2192 ${basename(uniqueTargetFile)}`);
56095
56330
  continue;
56096
56331
  } catch (renameError) {
56097
56332
  conflicts.push({
@@ -56129,7 +56364,7 @@ const programmaticFileCopyStep = createStep({
56129
56364
  id: unit.id
56130
56365
  }
56131
56366
  });
56132
- console.info(`✓ Copied ${unit.kind} "${unit.id}": ${unit.file} → ${convertedFileName}`);
56367
+ console.info(`\u2713 Copied ${unit.kind} "${unit.id}": ${unit.file} \u2192 ${convertedFileName}`);
56133
56368
  } catch (copyError) {
56134
56369
  conflicts.push({
56135
56370
  unit: {
@@ -56156,7 +56391,7 @@ const programmaticFileCopyStep = createStep({
56156
56391
  id: "tsconfig.json"
56157
56392
  }
56158
56393
  });
56159
- console.info("✓ Copied tsconfig.json from template to target");
56394
+ console.info("\u2713 Copied tsconfig.json from template to target");
56160
56395
  } else {
56161
56396
  await writeFile(targetTsconfig, JSON.stringify({
56162
56397
  compilerOptions: {
@@ -56192,7 +56427,7 @@ const programmaticFileCopyStep = createStep({
56192
56427
  id: "tsconfig.json"
56193
56428
  }
56194
56429
  });
56195
- console.info("✓ Generated minimal tsconfig.json in target");
56430
+ console.info("\u2713 Generated minimal tsconfig.json in target");
56196
56431
  }
56197
56432
  }
56198
56433
  } catch (e) {
@@ -56221,7 +56456,7 @@ const programmaticFileCopyStep = createStep({
56221
56456
  id: "mastra-index"
56222
56457
  }
56223
56458
  });
56224
- console.info("✓ Copied Mastra index file from template");
56459
+ console.info("\u2713 Copied Mastra index file from template");
56225
56460
  }
56226
56461
  }
56227
56462
  } catch (e) {
@@ -56250,7 +56485,7 @@ const programmaticFileCopyStep = createStep({
56250
56485
  id: "gitignore"
56251
56486
  }
56252
56487
  });
56253
- console.info("✓ Copied .gitignore from template to target");
56488
+ console.info("\u2713 Copied .gitignore from template to target");
56254
56489
  } else {
56255
56490
  const targetContent = await readFile(targetGitignore, "utf-8");
56256
56491
  const templateContent = await readFile(templateGitignore, "utf-8");
@@ -56266,8 +56501,8 @@ const programmaticFileCopyStep = createStep({
56266
56501
  id: "gitignore-merge"
56267
56502
  }
56268
56503
  });
56269
- console.info(`✓ Merged template .gitignore entries into existing .gitignore (${addedLines} new entries)`);
56270
- } else console.info("ℹ No new .gitignore entries to add from template");
56504
+ console.info(`\u2713 Merged template .gitignore entries into existing .gitignore (${addedLines} new entries)`);
56505
+ } else console.info("\u2139 No new .gitignore entries to add from template");
56271
56506
  }
56272
56507
  }
56273
56508
  } catch (e) {
@@ -56296,7 +56531,7 @@ const programmaticFileCopyStep = createStep({
56296
56531
  id: "env"
56297
56532
  }
56298
56533
  });
56299
- console.info(`✓ Created .env file with ${Object.keys(variables).length} template variables`);
56534
+ console.info(`\u2713 Created .env file with ${Object.keys(variables).length} template variables`);
56300
56535
  } else {
56301
56536
  const targetContent = await readFile(targetEnv, "utf-8");
56302
56537
  const mergedContent = mergeEnvFiles(targetContent, variables, slug);
@@ -56311,8 +56546,8 @@ const programmaticFileCopyStep = createStep({
56311
56546
  id: "env-merge"
56312
56547
  }
56313
56548
  });
56314
- console.info(`✓ Merged new environment variables into existing .env file (${addedLines} new entries)`);
56315
- } else console.info("ℹ No new environment variables to add (all already exist in .env)");
56549
+ console.info(`\u2713 Merged new environment variables into existing .env file (${addedLines} new entries)`);
56550
+ } else console.info("\u2139 No new environment variables to add (all already exist in .env)");
56316
56551
  }
56317
56552
  }
56318
56553
  } catch (e) {
@@ -56329,7 +56564,7 @@ const programmaticFileCopyStep = createStep({
56329
56564
  if (copiedFiles.length > 0) try {
56330
56565
  const fileList = copiedFiles.map((f) => f.destination);
56331
56566
  await gitAddAndCommit(targetPath, `feat(template): copy ${copiedFiles.length} files from ${slug}@${commitSha.substring(0, 7)}`, fileList, { skipIfNoStaged: true });
56332
- console.info(`✓ Committed ${copiedFiles.length} copied files`);
56567
+ console.info(`\u2713 Committed ${copiedFiles.length} copied files`);
56333
56568
  } catch (commitError) {
56334
56569
  console.warn("Failed to commit copied files:", commitError);
56335
56570
  }
@@ -56573,7 +56808,7 @@ Start by listing your tasks and work through them systematically!
56573
56808
  content: toolResult.content || "",
56574
56809
  notes: toolResult.notes
56575
56810
  });
56576
- console.info(`📋 Task completed: ${toolResult.taskId} - ${toolResult.content}`);
56811
+ console.info(`\u{1F4CB} Task completed: ${toolResult.taskId} - ${toolResult.content}`);
56577
56812
  }
56578
56813
  } catch (parseError) {
56579
56814
  console.warn("Failed to parse task management result:", parseError);
@@ -56625,7 +56860,7 @@ const validationAndFixStep = createStep({
56625
56860
  const { commitSha, slug, orderedUnits, templateDir, copiedFiles, conflictsResolved, maxIterations = 5 } = inputData;
56626
56861
  const targetPath = resolveTargetPath(inputData, requestContext);
56627
56862
  if (!(copiedFiles.length > 0 || conflictsResolved && conflictsResolved.length > 0)) {
56628
- console.info("⏭️ Skipping validation - no files copied or conflicts resolved");
56863
+ console.info("\u23ED\uFE0F Skipping validation - no files copied or conflicts resolved");
56629
56864
  return {
56630
56865
  success: true,
56631
56866
  applied: false,
@@ -56637,7 +56872,7 @@ const validationAndFixStep = createStep({
56637
56872
  }
56638
56873
  };
56639
56874
  }
56640
- console.info(`📋 Changes detected: ${copiedFiles.length} files copied, ${conflictsResolved?.length || 0} conflicts resolved`);
56875
+ console.info(`\u{1F4CB} Changes detected: ${copiedFiles.length} files copied, ${conflictsResolved?.length || 0} conflicts resolved`);
56641
56876
  let currentIteration = 1;
56642
56877
  try {
56643
56878
  const model = await resolveModel({
@@ -56729,7 +56964,7 @@ CRITICAL TOOL SELECTION GUIDE:
56729
56964
  - **writeFile**: ONLY for creating new files that don't exist
56730
56965
  Example: creating missing index.ts barrel files
56731
56966
 
56732
- CRITICAL WRITEFILЕ SAFETY RULES:
56967
+ CRITICAL WRITEFIL\u0415 SAFETY RULES:
56733
56968
  - ONLY use writeFile for creating NEW files that don't exist
56734
56969
  - ALWAYS check with readFile first to verify file doesn't exist
56735
56970
  - NEVER use writeFile to overwrite existing files - use multiEdit or replaceLines instead
@@ -56814,10 +57049,10 @@ Previous iterations may have fixed some issues, so start by re-running validateC
56814
57049
  if (iterationErrors > 0 && lastValidationResult?.errors) validationResults.lastValidationErrors = lastValidationResult.errors;
56815
57050
  console.info(`Iteration ${currentIteration} complete: ${iterationErrors} errors remaining`);
56816
57051
  if (iterationErrors === 0) {
56817
- console.info(`✅ All validation issues resolved in ${currentIteration} iterations!`);
57052
+ console.info(`\u2705 All validation issues resolved in ${currentIteration} iterations!`);
56818
57053
  break;
56819
57054
  } else if (currentIteration >= maxIterations) {
56820
- console.info(`⚠️ Max iterations (${maxIterations}) reached. ${iterationErrors} errors still remaining.`);
57055
+ console.info(`\u26A0\uFE0F Max iterations (${maxIterations}) reached. ${iterationErrors} errors still remaining.`);
56821
57056
  break;
56822
57057
  }
56823
57058
  currentIteration++;
@@ -56857,7 +57092,7 @@ Previous iterations may have fixed some issues, so start by re-running validateC
56857
57092
  recursive: true,
56858
57093
  force: true
56859
57094
  });
56860
- console.info(`✓ Cleaned up template directory: ${templateDir}`);
57095
+ console.info(`\u2713 Cleaned up template directory: ${templateDir}`);
56861
57096
  } catch (cleanupError) {
56862
57097
  console.warn("Failed to cleanup template directory:", cleanupError);
56863
57098
  }
@@ -59951,11 +60186,11 @@ function createPlanningAndApprovalWorkflow() {
59951
60186
  }
59952
60187
  createPlanningAndApprovalWorkflow();
59953
60188
  const workflowResearch = `
59954
- ## 🔍 **COMPREHENSIVE MASTRA WORKFLOW RESEARCH SUMMARY**
60189
+ ## \u{1F50D} **COMPREHENSIVE MASTRA WORKFLOW RESEARCH SUMMARY**
59955
60190
 
59956
60191
  Based on extensive research of Mastra documentation and examples, here's essential information for building effective Mastra workflows:
59957
60192
 
59958
- ### **📋 WORKFLOW FUNDAMENTALS**
60193
+ ### **\u{1F4CB} WORKFLOW FUNDAMENTALS**
59959
60194
 
59960
60195
  **Core Components:**
59961
60196
  - **\`createWorkflow()\`**: Main factory function that creates workflow instances
@@ -59979,7 +60214,7 @@ const workflow = createWorkflow({
59979
60214
  .commit(); // CRITICAL: Makes workflow executable
59980
60215
  \`\`\`
59981
60216
 
59982
- ### **🔧 STEP CREATION PATTERNS**
60217
+ ### **\u{1F527} STEP CREATION PATTERNS**
59983
60218
 
59984
60219
  **Standard Step Definition:**
59985
60220
  \`\`\`typescript
@@ -60003,7 +60238,7 @@ const myStep = createStep({
60003
60238
  - \`requestContext\`: Runtime dependency injection context
60004
60239
  - \`runCount\`: Number of times this step has run (useful for retries)
60005
60240
 
60006
- ### **🔄 CONTROL FLOW METHODS**
60241
+ ### **\u{1F504} CONTROL FLOW METHODS**
60007
60242
 
60008
60243
  **Sequential Execution:**
60009
60244
  - \`.then(step)\`: Execute steps one after another
@@ -60025,7 +60260,7 @@ const myStep = createStep({
60025
60260
  **Data Transformation:**
60026
60261
  - \`.map(({ inputData, getStepResult, getInitData }) => transformedData)\`: Transform data between steps
60027
60262
 
60028
- ### **⏸️ SUSPEND & RESUME CAPABILITIES**
60263
+ ### **\u23F8\uFE0F SUSPEND & RESUME CAPABILITIES**
60029
60264
 
60030
60265
  **For Human-in-the-Loop Workflows:**
60031
60266
  \`\`\`typescript
@@ -60056,7 +60291,7 @@ if (result.status === "suspended") {
60056
60291
  }
60057
60292
  \`\`\`
60058
60293
 
60059
- ### **🛠️ INTEGRATING AGENTS & TOOLS**
60294
+ ### **\u{1F6E0}\uFE0F INTEGRATING AGENTS & TOOLS**
60060
60295
 
60061
60296
  **Using Agents in Steps:**
60062
60297
  \`\`\`typescript
@@ -60089,24 +60324,24 @@ const step = createStep({
60089
60324
  });
60090
60325
  \`\`\`
60091
60326
 
60092
- ### **🗂️ PROJECT ORGANIZATION PATTERNS**
60327
+ ### **\u{1F5C2}\uFE0F PROJECT ORGANIZATION PATTERNS**
60093
60328
 
60094
60329
  **MANDATORY Workflow Organization:**
60095
60330
  Each workflow MUST be organized in its own dedicated folder with separated concerns:
60096
60331
 
60097
60332
  \`\`\`
60098
60333
  src/mastra/workflows/
60099
- ├── my-workflow-name/ # Kebab-case folder name
60100
- │ ├── types.ts # All Zod schemas and TypeScript types
60101
- │ ├── steps.ts # All individual step definitions
60102
- │ ├── workflow.ts # Main workflow composition and export
60103
- │ └── utils.ts # Helper functions (if needed)
60104
- ├── another-workflow/
60105
- │ ├── types.ts
60106
- │ ├── steps.ts
60107
- │ ├── workflow.ts
60108
- │ └── utils.ts
60109
- └── index.ts # Export all workflows
60334
+ \u251C\u2500\u2500 my-workflow-name/ # Kebab-case folder name
60335
+ \u2502 \u251C\u2500\u2500 types.ts # All Zod schemas and TypeScript types
60336
+ \u2502 \u251C\u2500\u2500 steps.ts # All individual step definitions
60337
+ \u2502 \u251C\u2500\u2500 workflow.ts # Main workflow composition and export
60338
+ \u2502 \u2514\u2500\u2500 utils.ts # Helper functions (if needed)
60339
+ \u251C\u2500\u2500 another-workflow/
60340
+ \u2502 \u251C\u2500\u2500 types.ts
60341
+ \u2502 \u251C\u2500\u2500 steps.ts
60342
+ \u2502 \u251C\u2500\u2500 workflow.ts
60343
+ \u2502 \u2514\u2500\u2500 utils.ts
60344
+ \u2514\u2500\u2500 index.ts # Export all workflows
60110
60345
  \`\`\`
60111
60346
 
60112
60347
  **CRITICAL File Organization Rules:**
@@ -60130,7 +60365,7 @@ export const mastra = new Mastra({
60130
60365
  });
60131
60366
  \`\`\`
60132
60367
 
60133
- ### **📦 ESSENTIAL DEPENDENCIES**
60368
+ ### **\u{1F4E6} ESSENTIAL DEPENDENCIES**
60134
60369
 
60135
60370
  **Required Packages:**
60136
60371
  \`\`\`json
@@ -60147,7 +60382,7 @@ export const mastra = new Mastra({
60147
60382
  - \`@ai-sdk/openai\`: For AI model integration
60148
60383
  - \`ai\`: For AI SDK functionality
60149
60384
 
60150
- ### **✅ WORKFLOW BEST PRACTICES**
60385
+ ### **\u2705 WORKFLOW BEST PRACTICES**
60151
60386
 
60152
60387
  **Schema Design:**
60153
60388
  - Use descriptive property names in schemas
@@ -60169,7 +60404,7 @@ export const mastra = new Mastra({
60169
60404
  - Access previous step results with \`getStepResult(stepInstance)\`
60170
60405
  - Use \`getInitData()\` to access original workflow input
60171
60406
 
60172
- ### **🚀 EXECUTION PATTERNS**
60407
+ ### **\u{1F680} EXECUTION PATTERNS**
60173
60408
 
60174
60409
  **Running Workflows:**
60175
60410
  \`\`\`typescript
@@ -60192,7 +60427,7 @@ run.watch((event) => console.log(event));
60192
60427
  - \`"suspended"\`: Paused awaiting input
60193
60428
  - \`"failed"\`: Encountered error
60194
60429
 
60195
- ### **🔗 ADVANCED FEATURES**
60430
+ ### **\u{1F517} ADVANCED FEATURES**
60196
60431
 
60197
60432
  **Nested Workflows:**
60198
60433
  - Use workflows as steps: \`.then(otherWorkflow)\`
@@ -60255,11 +60490,11 @@ CRITICAL WORKFLOW EXECUTION REQUIREMENTS:
60255
60490
  MANDATORY WORKFLOW FOLDER STRUCTURE:
60256
60491
  When ${context.action === "create" ? "creating a new workflow" : "editing a workflow"}, you MUST organize files as follows:
60257
60492
 
60258
- 📁 src/mastra/workflows/${context.workflowName?.toLowerCase().replace(/[^a-z0-9]/g, "-") || "new-workflow"}/
60259
- ├── 📄 types.ts # All Zod schemas and TypeScript types
60260
- ├── 📄 steps.ts # All individual step definitions
60261
- ├── 📄 workflow.ts # Main workflow composition and export
60262
- └── 📄 utils.ts # Helper functions (if needed)
60493
+ \u{1F4C1} src/mastra/workflows/${context.workflowName?.toLowerCase().replace(/[^a-z0-9]/g, "-") || "new-workflow"}/
60494
+ \u251C\u2500\u2500 \u{1F4C4} types.ts # All Zod schemas and TypeScript types
60495
+ \u251C\u2500\u2500 \u{1F4C4} steps.ts # All individual step definitions
60496
+ \u251C\u2500\u2500 \u{1F4C4} workflow.ts # Main workflow composition and export
60497
+ \u2514\u2500\u2500 \u{1F4C4} utils.ts # Helper functions (if needed)
60263
60498
 
60264
60499
  CRITICAL FILE ORGANIZATION RULES:
60265
60500
  - **ALWAYS create a dedicated folder** for the workflow in src/mastra/workflows/
@@ -60331,7 +60566,7 @@ ${context.resumeData ? `USER PROVIDED ANSWERS: ${JSON.stringify(context.resumeDa
60331
60566
  },
60332
60567
  validation: { instructions: `CRITICAL VALIDATION INSTRUCTIONS:
60333
60568
  - When using the validateCode tool, ALWAYS pass the specific files you created or modified using the 'files' parameter
60334
- - The tool uses a hybrid validation approach: fast syntax checking → semantic type checking → ESLint
60569
+ - The tool uses a hybrid validation approach: fast syntax checking \u2192 semantic type checking \u2192 ESLint
60335
60570
  - This is much faster than full project compilation and only shows errors from your specific files
60336
60571
  - Example: validateCode({ validationType: ['types', 'lint'], files: ['src/workflows/my-workflow.ts', 'src/agents/my-agent.ts'] })
60337
60572
  - ALWAYS validate after creating or modifying files to ensure they compile correctly` }