@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.
- package/dist/{a2a-WPGF38fX.js → a2a-CY7rgzPe.js} +1 -1
- package/dist/{a2a-vSZkdSRE.cjs → a2a-DwjvHqcb.cjs} +1 -1
- package/dist/{agent-builder-C4AIqOxt.js → agent-builder-DHnNRROR.js} +2 -2
- package/dist/{agent-builder-dZlRNj1k.cjs → agent-builder-anRH1X35.cjs} +2 -2
- package/dist/{agent-controller-BHJDvCaS.cjs → agent-controller-BP-CFfsg.cjs} +9 -9
- package/dist/{agent-controller-NRR6SK66.js → agent-controller-CzKnfKkw.js} +9 -9
- package/dist/{agent-versions-CwWhEoU5.cjs → agent-versions-0q4KKmLv.cjs} +12 -12
- package/dist/{agent-versions-DfcKpYNW.js → agent-versions-Pml6WNbA.js} +12 -12
- package/dist/{agents-272TP94y.js → agents-CAXsXenf.js} +32 -3
- package/dist/{agents-mjQZV5tv.cjs → agents-GHhuyz5x.cjs} +32 -3
- package/dist/{api-schema-manifest-BjhiTdNv.js → api-schema-manifest-4PK1dBWt.js} +1 -1
- package/dist/{api-schema-manifest-DVkepK_s.cjs → api-schema-manifest-CX16hC7V.cjs} +1 -1
- package/dist/{auth-CM5AgF9l.cjs → auth-BR7vRIrY.cjs} +5 -3
- package/dist/{auth-CjT_a76k.js → auth-ChZ3dUvo.js} +5 -3
- package/dist/{catalogue-DH64Duv-.js → catalogue-BOzHZ1xt.js} +11 -11
- package/dist/{catalogue-BTE9b_mr.cjs → catalogue-DNy7Fog6.cjs} +11 -11
- package/dist/{conversations-CXyaNjLR.js → conversations-BjD8wOc3.js} +1 -1
- package/dist/{conversations-BWA_---j.cjs → conversations-CgogBOHO.cjs} +1 -1
- package/dist/{datasets-C1XJLHN8.js → datasets-CYdtUF8e.js} +4 -1
- package/dist/{datasets-hqDd4IUN.cjs → datasets-CZRqni0N.cjs} +4 -1
- package/dist/dist-BWVxgpEw.js +1 -0
- package/dist/{dist-DGwsCtT4.cjs → dist-Brw_H26B.cjs} +521 -286
- package/dist/{dist-CSffo32A.cjs → dist-C5_WGwU1.cjs} +1 -1
- package/dist/{dist-Bp1bObAq.js → dist-NBGkHBIE.js} +521 -286
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/docs/references/docs-knowledge-overview.md +1 -1
- package/dist/docs/references/reference-observability-tracing-advanced-queries.md +20 -0
- package/dist/{dynamic-workflows-DPgV6qtS.cjs → dynamic-workflows-CEKdGcSr.cjs} +4 -4
- package/dist/{dynamic-workflows-DmkCJ4Lp.js → dynamic-workflows-DF9X_oDG.js} +4 -4
- package/dist/{editor-builder-BayzCprJ.js → editor-builder-BRzXnsRW.js} +1 -1
- package/dist/{editor-builder-BS2xogE_.cjs → editor-builder-G1ub9j0s.cjs} +1 -1
- package/dist/{knowledge-DL03nbSW.cjs → knowledge-B3768ERP.cjs} +1 -0
- package/dist/{knowledge-DAqUHFK5.js → knowledge-wqC0nrmu.js} +1 -0
- package/dist/{observability-zr7LDCQG.js → observability-URaJnI_U.js} +1 -1
- package/dist/{observability-Cn4P60P4.cjs → observability-zNA_CVaz.cjs} +1 -1
- package/dist/{plans-xGwuiZUd.js → plans-DGC1grMp.js} +1 -1
- package/dist/{plans-Bes_LVgv.cjs → plans-kA8E3Auv.cjs} +1 -1
- package/dist/probe-image-size-ntJyQKKB.cjs +13304 -0
- package/dist/probe-image-size-zXQBlFaQ.js +13297 -0
- package/dist/{responses-CwQO5y2X.js → responses--nGf7l3O.js} +1 -1
- package/dist/{responses-BH567IZf.cjs → responses-B4GDz-Nm.cjs} +1 -1
- package/dist/{routes-CrBCJmjc.js → routes-BZVlqLly.js} +17 -17
- package/dist/{routes-6p-xrUIq.cjs → routes-vuZLexcc.cjs} +17 -17
- package/dist/{schedules-0ceTSdBB.cjs → schedules-CwL28Eca.cjs} +4 -4
- package/dist/{schedules-D_VfFdAH.js → schedules-RWgPeypN.js} +4 -4
- package/dist/{scorer-versions-Bhdvt-cX.cjs → scorer-versions-DK-PGj7-.cjs} +1 -1
- package/dist/{scorer-versions-DhT7Lj33.js → scorer-versions-oJoK2Exw.js} +1 -1
- package/dist/{scores-ksmJiJnJ.js → scores-Biv7XGW_.js} +1 -1
- package/dist/{scores-CXNkN7Bn.cjs → scores-D0Qq7TfU.cjs} +1 -1
- package/dist/server/handlers/a2a.cjs +1 -1
- package/dist/server/handlers/a2a.js +1 -1
- package/dist/server/handlers/agent-builder.cjs +1 -1
- package/dist/server/handlers/agent-builder.js +1 -1
- package/dist/server/handlers/agent-controller.cjs +1 -1
- package/dist/server/handlers/agent-controller.js +1 -1
- package/dist/server/handlers/agent-versions.cjs +1 -1
- package/dist/server/handlers/agent-versions.js +1 -1
- package/dist/server/handlers/agents.cjs +1 -1
- package/dist/server/handlers/agents.js +1 -1
- package/dist/server/handlers/auth.cjs +7 -3
- package/dist/server/handlers/auth.d.ts +12 -4
- package/dist/server/handlers/auth.js +7 -3
- package/dist/server/handlers/conversations.cjs +1 -1
- package/dist/server/handlers/conversations.js +1 -1
- package/dist/server/handlers/datasets.cjs +16 -11
- package/dist/server/handlers/datasets.d.ts +6 -0
- package/dist/server/handlers/datasets.js +16 -11
- package/dist/server/handlers/dynamic-workflows.cjs +1 -1
- package/dist/server/handlers/dynamic-workflows.js +1 -1
- package/dist/server/handlers/editor-builder.cjs +1 -1
- package/dist/server/handlers/editor-builder.js +1 -1
- package/dist/server/handlers/error.cjs +1 -1
- package/dist/server/handlers/error.js +1 -1
- package/dist/server/handlers/favorites-enrichment.cjs +1 -1
- package/dist/server/handlers/favorites-enrichment.js +1 -1
- package/dist/server/handlers/knowledge.cjs +1 -1
- package/dist/server/handlers/knowledge.js +1 -1
- package/dist/server/handlers/observability.cjs +1 -1
- package/dist/server/handlers/observability.js +1 -1
- package/dist/server/handlers/plans.cjs +1 -1
- package/dist/server/handlers/plans.js +1 -1
- package/dist/server/handlers/responses.cjs +1 -1
- package/dist/server/handlers/responses.js +1 -1
- package/dist/server/handlers/schedules.cjs +1 -1
- package/dist/server/handlers/schedules.js +1 -1
- package/dist/server/handlers/scorer-versions.cjs +1 -1
- package/dist/server/handlers/scorer-versions.js +1 -1
- package/dist/server/handlers/scores.cjs +1 -1
- package/dist/server/handlers/scores.js +1 -1
- package/dist/server/handlers/stored-agent-favorites.cjs +3 -3
- package/dist/server/handlers/stored-agent-favorites.js +3 -3
- package/dist/server/handlers/stored-agents.cjs +2 -2
- package/dist/server/handlers/stored-agents.js +2 -2
- package/dist/server/handlers/stored-scorers.cjs +1 -1
- package/dist/server/handlers/stored-scorers.js +1 -1
- package/dist/server/handlers/stored-skill-favorites.cjs +2 -2
- package/dist/server/handlers/stored-skill-favorites.js +2 -2
- package/dist/server/handlers/stored-skills.cjs +1 -1
- package/dist/server/handlers/stored-skills.js +1 -1
- package/dist/server/handlers/system.cjs +1 -1
- package/dist/server/handlers/system.js +1 -1
- package/dist/server/handlers/tool-providers.cjs +2 -2
- package/dist/server/handlers/tool-providers.js +2 -2
- package/dist/server/handlers/tools.cjs +1 -1
- package/dist/server/handlers/tools.js +1 -1
- package/dist/server/handlers/voice.cjs +1 -1
- package/dist/server/handlers/voice.js +1 -1
- package/dist/server/handlers/workflows.cjs +1 -1
- package/dist/server/handlers/workflows.js +1 -1
- package/dist/server/handlers.cjs +12 -12
- package/dist/server/handlers.js +12 -12
- package/dist/server/schemas/auth.d.ts +3 -1
- package/dist/server/schemas/datasets.d.ts +3 -0
- package/dist/server/schemas/index.cjs +7 -7
- package/dist/server/schemas/index.js +7 -7
- package/dist/server/server-adapter/index.cjs +3 -3
- package/dist/server/server-adapter/index.js +3 -3
- package/dist/server/server-adapter/routes/datasets.d.ts +6 -0
- package/dist/{server-adapter-Ceag3til.cjs → server-adapter-CurME3ch.cjs} +4 -4
- package/dist/{server-adapter-BGOi-s7x.js → server-adapter-h8YRQXAC.js} +4 -4
- package/dist/{stored-agents-m0Knvv29.cjs → stored-agents-BS4_LGSs.cjs} +32 -32
- package/dist/{stored-agents-DmN_pIIl.js → stored-agents-DcyDMKP2.js} +32 -32
- package/dist/{stored-scorers-2F2k6XSx.js → stored-scorers-Bdz_5k57.js} +1 -1
- package/dist/{stored-scorers-iM2Qq9Nh.cjs → stored-scorers-D8YYszOj.cjs} +1 -1
- package/dist/{tool-providers-Cq3vFqgE.js → tool-providers-BN2Ni06Z.js} +2 -2
- package/dist/{tool-providers-BVwRJTtB.cjs → tool-providers-BeiSkVHu.cjs} +2 -2
- package/dist/{tools-DLZ7go-n.cjs → tools-By0RVh_O.cjs} +1 -1
- package/dist/{tools-CY44YtDW.js → tools-C3KBdlil.js} +1 -1
- package/dist/{voice-NaerSeVQ.cjs → voice-CESew8Fc.cjs} +1 -1
- package/dist/{voice-DTjrAgqg.js → voice-PfxY_vQg.js} +1 -1
- package/dist/{workflows-gIKukZ1O.cjs → workflows-CHKSHV4f.cjs} +33 -0
- package/dist/{workflows-D3QrUMfm.js → workflows-D5bfbang.js} +33 -0
- package/package.json +3 -3
- package/dist/dist-Bn0zFASI.js +0 -1
- package/dist/probe-image-size-BR5MlnnJ.cjs +0 -13304
- package/dist/probe-image-size-DBCcUUw_.js +0 -13297
|
@@ -7,12 +7,12 @@ zod_v4 = require_rolldown_runtime.__toESM(zod_v4, 1);
|
|
|
7
7
|
let _mastra_core_schema = require("@mastra/core/schema");
|
|
8
8
|
let zod_v3 = require("zod/v3");
|
|
9
9
|
let zod = require("zod");
|
|
10
|
+
let util = require("util");
|
|
10
11
|
let _mastra_core_memory = require("@mastra/core/memory");
|
|
11
12
|
let _mastra_core_agent = require("@mastra/core/agent");
|
|
12
13
|
let _mastra_core_error = require("@mastra/core/error");
|
|
13
14
|
let _mastra_core_llm = require("@mastra/core/llm");
|
|
14
15
|
let _mastra_core_tools = require("@mastra/core/tools");
|
|
15
|
-
let util = require("util");
|
|
16
16
|
let _mastra_core_request_context = require("@mastra/core/request-context");
|
|
17
17
|
let _mastra_core_utils = require("@mastra/core/utils");
|
|
18
18
|
let _mastra_core_storage = require("@mastra/core/storage");
|
|
@@ -897,7 +897,7 @@ var require_jpeg = /* @__PURE__ */ require_rolldown_runtime.__commonJSMin(((expo
|
|
|
897
897
|
var str2arr = require_utils().str2arr;
|
|
898
898
|
var sliceEq = require_utils().sliceEq;
|
|
899
899
|
var exifOrientation = require_exif_orientation_parser();
|
|
900
|
-
var SIG_JPEG = str2arr("
|
|
900
|
+
var SIG_JPEG = str2arr("\u00FF\u00D8\u00FF");
|
|
901
901
|
var SIG_EXIF = str2arr("Exif\0\0");
|
|
902
902
|
var S_SIGNATURE = 0;
|
|
903
903
|
var S_MARKER_START = 1;
|
|
@@ -1043,7 +1043,7 @@ var require_png = /* @__PURE__ */ require_rolldown_runtime.__commonJSMin(((expor
|
|
|
1043
1043
|
var str2arr = require_utils().str2arr;
|
|
1044
1044
|
var sliceEq = require_utils().sliceEq;
|
|
1045
1045
|
var readUInt32BE = require_read_le_be().readUInt32BE;
|
|
1046
|
-
var SIG_PNG = str2arr("
|
|
1046
|
+
var SIG_PNG = str2arr("\u0089PNG\r\n\n");
|
|
1047
1047
|
var SIG_IHDR = str2arr("IHDR");
|
|
1048
1048
|
function PngParser() {
|
|
1049
1049
|
this.partial_buffer = /* @__PURE__ */ new Uint8Array(24);
|
|
@@ -8656,7 +8656,7 @@ function splitLines(text) {
|
|
|
8656
8656
|
else result.push(result.pop().slice(0, -1));
|
|
8657
8657
|
return result;
|
|
8658
8658
|
}
|
|
8659
|
-
// ../memory/dist/src-
|
|
8659
|
+
// ../memory/dist/src-C6oJP8WI.js
|
|
8660
8660
|
var __defProp$3 = Object.defineProperty;
|
|
8661
8661
|
var __exportAll = (all, no_symbols) => {
|
|
8662
8662
|
let target = {};
|
|
@@ -32877,14 +32877,14 @@ function getRetrievalInstructions(scope = "resource", customInstructions, search
|
|
|
32877
32877
|
The recall tool works across ALL of this user's conversation threads, not just the current one.
|
|
32878
32878
|
|
|
32879
32879
|
- Use \`mode: "search"\` with a \`query\` to find relevant history, even when you already know the thread. Each result includes its thread ID, observation group ID, and source message range.
|
|
32880
|
-
- Use \`mode: "messages"\` for original wording or details behind an observation
|
|
32880
|
+
- Use \`mode: "messages"\` for original wording or details behind an observation \u2014 pass \`threadId\` to read another thread and a \`cursor\` from the source message range.
|
|
32881
32881
|
- Use \`mode: "threads"\` to list the user's threads (IDs, titles, dates) when you need to discover where something was discussed. Use \`before\`/\`after\` to narrow by date.
|
|
32882
32882
|
|
|
32883
|
-
**If search results look irrelevant, do not give up.** Search only covers content that has been indexed
|
|
32883
|
+
**If search results look irrelevant, do not give up.** Search only covers content that has been indexed \u2014 a short or recent conversation may exist in raw message history before any observation of it was created. When search returns nothing suitable but the user is clearly referring to a past conversation, call \`mode: "threads"\` to find candidate threads (titles and dates are strong clues), then read them with \`mode: "messages"\`. Use a useful hit as an entry point to the surrounding history rather than treating it as the whole answer.` : `### Choosing a mode
|
|
32884
32884
|
The recall tool works across ALL of this user's conversation threads, not just the current one.
|
|
32885
32885
|
|
|
32886
32886
|
- Use \`mode: "threads"\` to list the user's threads (IDs, titles, dates) when you need to discover where something was discussed. Use \`before\`/\`after\` to narrow by date.
|
|
32887
|
-
- Use \`mode: "messages"\` when you know the thread
|
|
32887
|
+
- Use \`mode: "messages"\` when you know the thread \u2014 pass \`threadId\` to read another thread, or a \`cursor\` from an observation-group range.
|
|
32888
32888
|
|
|
32889
32889
|
When the user refers to a past conversation you don't have a cursor for, call \`mode: "threads"\` to find candidate threads (titles and dates are strong clues), then read them with \`mode: "messages"\`. Raw history may exist for threads that have no observations yet.` : `### Choosing a mode
|
|
32890
32890
|
The recall tool is limited to the current conversation thread.
|
|
@@ -32909,7 +32909,7 @@ When searches keep returning the same groups, often as already-in-context refere
|
|
|
32909
32909
|
"Excerpt already in current context" marks a hit whose text an earlier search result already shows. "Group already in current context" marks a group that is already in your observations or whose source messages are still in the conversation. "Source range overlaps current context" marks a group whose source messages are still in the conversation. Search keeps these references and tries lower-ranked matches to fill the requested number of excerpts. This backfill is bounded: fewer excerpts do not mean history is exhausted. Use the evidence already present rather than repeating the same lookup. You can still ${pagingEnabled ? "page a referenced group" : "read a referenced group's source messages"} when you need all of it, or search again if that context is no longer available.
|
|
32910
32910
|
|
|
32911
32911
|
If search still finds nothing useful, browse raw messages${isResource ? " or discover other threads" : " in this thread"} before concluding the information is unavailable. Raw history may exist for threads that have no observations yet.` : "";
|
|
32912
|
-
const base = `## Recall
|
|
32912
|
+
const base = `## Recall \u2014 looking up source messages
|
|
32913
32913
|
|
|
32914
32914
|
Your memory contains observation groups with IDs and source message ranges, shown as \`## Group\` headings with \`_range: startId:endId\` or as \`<observation-group>\` tags. Use the **recall** tool to recover retained original observations and source messages.
|
|
32915
32915
|
|
|
@@ -32920,13 +32920,13 @@ Groups marked \`kind="reflection"\` (rendered as \`_kind: reflection_\`) are los
|
|
|
32920
32920
|
|
|
32921
32921
|
### When to use recall
|
|
32922
32922
|
- The user asks you to **repeat, show, or reproduce** something from a past conversation
|
|
32923
|
-
- The user asks for **exact content**
|
|
32923
|
+
- The user asks for **exact content** \u2014 code, text, quotes, error messages, URLs, file paths, specific numbers
|
|
32924
32924
|
- Your observations mention something but your memory lacks the detail needed to fully answer (e.g. you know a blog post was shared but only have a summary of it)
|
|
32925
32925
|
- You want to **verify or expand on** an observation before responding
|
|
32926
32926
|
- The answer depends on historical dates, order, or duration: verify both event dates and that they refer to the events the user means. Distinguish a plan, an actual start, a later update, and a repeated mention instead of choosing a nearby date from a summary
|
|
32927
32927
|
- An observation records something the assistant proposed, such as a schedule, date, or plan, and your observations don't show what the user decided. Read the raw messages around it to find the user's decision before treating the proposal as what happened
|
|
32928
32928
|
- Relevant details are missing, ambiguous, or conflicting in the current observations${isResource ? `
|
|
32929
|
-
- The user references another conversation that your observations don't cover
|
|
32929
|
+
- The user references another conversation that your observations don't cover \u2014 even if you have no observations yet, their other threads may contain it` : ""}
|
|
32930
32930
|
|
|
32931
32931
|
**Default to using recall when the user references specific past content.** Your observations capture the gist, not the details. If there's any doubt whether your memory is complete enough, use recall.
|
|
32932
32932
|
|
|
@@ -32961,17 +32961,17 @@ Each range has the format \`startId:endId\` where both are message IDs separated
|
|
|
32961
32961
|
In \`mode: "messages"\`, recall returns **low** detail by default: truncated text and tool names only. Each message shows its ID and each part has a positional index like \`[p0]\`, \`[p1]\`, etc.
|
|
32962
32962
|
|
|
32963
32963
|
- Use \`detail: "high"\` to get full message content including tool arguments and results. This will only return the high detail version of a single message part at a time.
|
|
32964
|
-
- Use \`partIndex\` with a cursor to fetch a single part at full detail
|
|
32964
|
+
- Use \`partIndex\` with a cursor to fetch a single part at full detail \u2014 for example, to read one specific tool result or code block without loading every part.
|
|
32965
32965
|
|
|
32966
32966
|
If the result says \`truncated: true\`, the output was cut to fit the token budget. You can paginate or use \`partIndex\` to target specific content. If a single part is itself too large, follow the returned \`nextCharOffset\` as described below.
|
|
32967
32967
|
|
|
32968
32968
|
### Following up on truncated parts
|
|
32969
32969
|
Low-detail results may include truncation hints like:
|
|
32970
|
-
\`[truncated
|
|
32970
|
+
\`[truncated \u2014 call recall cursor="..." partIndex=N detail="high" for full content]\`
|
|
32971
32971
|
|
|
32972
32972
|
**When you see these hints and need the full content, make the exact call described in the hint.** This is the normal workflow: first recall at low detail to scan, then drill into specific parts at high detail. Do not stop at the low-detail result if the user asked for exact content.
|
|
32973
32973
|
|
|
32974
|
-
If a single part is larger than the token budget, the \`partIndex\` result is \`truncated: true\` and includes \`nextCharOffset\`. Repeat the same call with \`charOffset\` set to that exact value to read the next chunk from where the previous one ended. Keep following \`nextCharOffset\` until the result no longer includes it
|
|
32974
|
+
If a single part is larger than the token budget, the \`partIndex\` result is \`truncated: true\` and includes \`nextCharOffset\`. Repeat the same call with \`charOffset\` set to that exact value to read the next chunk from where the previous one ended. Keep following \`nextCharOffset\` until the result no longer includes it \u2014 the chunks together contain the full part. Retrying without \`charOffset\` returns the same prefix again.
|
|
32975
32975
|
|
|
32976
32976
|
### When recall is NOT needed
|
|
32977
32977
|
- The user is asking for a high-level summary and your observations already cover it
|
|
@@ -33366,6 +33366,15 @@ function buildThreadMetadataFromExtractedValues(extractors, values) {
|
|
|
33366
33366
|
async function applyExtractorHooks(opts) {
|
|
33367
33367
|
const values = normalizeExtractedValues(opts.values) ?? {};
|
|
33368
33368
|
const failures = [...opts.failures ?? []];
|
|
33369
|
+
let recentMessages;
|
|
33370
|
+
let recentMessagesResolved = false;
|
|
33371
|
+
const resolveRecentMessages = () => {
|
|
33372
|
+
if (!recentMessagesResolved) {
|
|
33373
|
+
recentMessages = typeof opts.recentMessages === "function" ? opts.recentMessages() : opts.recentMessages;
|
|
33374
|
+
recentMessagesResolved = true;
|
|
33375
|
+
}
|
|
33376
|
+
return recentMessages;
|
|
33377
|
+
};
|
|
33369
33378
|
for (const extractor of opts.extractors) {
|
|
33370
33379
|
const isHook = extractor.mode === "hook";
|
|
33371
33380
|
const hasValue = Object.prototype.hasOwnProperty.call(values, extractor.slug);
|
|
@@ -33385,7 +33394,9 @@ async function applyExtractorHooks(opts) {
|
|
|
33385
33394
|
previous: isHook ? void 0 : opts.previousValues?.[extractor.slug],
|
|
33386
33395
|
current,
|
|
33387
33396
|
rawObservations: opts.rawObservations,
|
|
33388
|
-
recentMessages
|
|
33397
|
+
get recentMessages() {
|
|
33398
|
+
return resolveRecentMessages();
|
|
33399
|
+
},
|
|
33389
33400
|
mainAgent: opts.mainAgent,
|
|
33390
33401
|
memory: opts.memory,
|
|
33391
33402
|
sendSignal: opts.sendSignal,
|
|
@@ -33629,6 +33640,17 @@ function isTransientLLMError(error) {
|
|
|
33629
33640
|
return visit(error);
|
|
33630
33641
|
}
|
|
33631
33642
|
/**
|
|
33643
|
+
* Returns true when the error says the provider account has no credits or quota left, as core's
|
|
33644
|
+
* provider-error classifier decides it. These can carry a retryable status (OpenAI's are HTTP 429,
|
|
33645
|
+
* the status of a rate limit), so `withRetry` stops on them even though `isTransientLLMError`
|
|
33646
|
+
* matches: the account stays unusable until someone adds credits. Rate limits are still retried.
|
|
33647
|
+
*
|
|
33648
|
+
* @internal
|
|
33649
|
+
*/
|
|
33650
|
+
function isExhaustedAccountError(error) {
|
|
33651
|
+
return (0, _mastra_core_error.classifyProviderError)(error) === "quota";
|
|
33652
|
+
}
|
|
33653
|
+
/**
|
|
33632
33654
|
* Compute the backoff delay (ms) for the Nth retry (0-indexed).
|
|
33633
33655
|
*
|
|
33634
33656
|
* Exponential growth (`initialDelayMs * backoffFactor^attempt`) capped at
|
|
@@ -33712,7 +33734,8 @@ async function attemptWithIdleTimeout(fn, label, idleTimeoutMs, abortSignal) {
|
|
|
33712
33734
|
/**
|
|
33713
33735
|
* Run `fn` with retries on transient transport-class errors.
|
|
33714
33736
|
*
|
|
33715
|
-
* Non-transient errors (auth, validation, schema, etc.)
|
|
33737
|
+
* Non-transient errors (auth, validation, schema, etc.) and errors from an
|
|
33738
|
+
* account with no credits or quota left (see `isExhaustedAccountError`) are rethrown
|
|
33716
33739
|
* immediately. User-initiated aborts are rethrown without delay.
|
|
33717
33740
|
*
|
|
33718
33741
|
* @internal
|
|
@@ -33728,7 +33751,7 @@ async function withRetry(fn, opts) {
|
|
|
33728
33751
|
} catch (error) {
|
|
33729
33752
|
if (abortSignal?.aborted) throw error;
|
|
33730
33753
|
if (!(error instanceof OmModelCallTimeoutError) && hasAbortInChain(error)) throw error;
|
|
33731
|
-
if (attempt >= maxRetries || !isTransientLLMError(error)) {
|
|
33754
|
+
if (attempt >= maxRetries || !isTransientLLMError(error) || isExhaustedAccountError(error)) {
|
|
33732
33755
|
if (attempt > 0) omDebug(`[OM:retry:${label}] giving up after ${attempt} retry/retries: ${error instanceof Error ? error.message : String(error)}`);
|
|
33733
33756
|
throw error;
|
|
33734
33757
|
}
|
|
@@ -34089,7 +34112,7 @@ const YEAR = String.raw`(?:19|20|21)\d{2}(?!\d)`;
|
|
|
34089
34112
|
const MERIDIEM = String.raw`(?:[AaPp]\.[Mm]\.|[AaPp][Mm]\b)`;
|
|
34090
34113
|
const TIME = String.raw`(?:,?\s+(?:at\s+)?\d{1,2}:\d{2}(?:\s*${MERIDIEM})?|\s+at\s+\d{1,2}\s*${MERIDIEM})`;
|
|
34091
34114
|
const QUALIFIER = String.raw`(?:(?:early|mid|late)[- ](?:to[- ](?:early|mid|late)[- ])?)`;
|
|
34092
|
-
const RANGE_SEP = String.raw`(?:\s*[
|
|
34115
|
+
const RANGE_SEP = String.raw`(?:\s*[\u2013\u2014]\s*|\s*-\s*|\s+(?:to|through|until)\s+)`;
|
|
34093
34116
|
/**
|
|
34094
34117
|
* Dates written into observation text that carry their own year, longest forms first:
|
|
34095
34118
|
* "Mar 1 - Mar 18, 2025", "May 27-28, 2023", "January 10, 2024 at 3:00 PM",
|
|
@@ -34390,15 +34413,15 @@ const SHORT_TOKEN_THRESHOLD = 3;
|
|
|
34390
34413
|
const KANA_CHARS_PER_TOKEN = 1.35;
|
|
34391
34414
|
const DEFAULT_LANGUAGE_CONFIGS = [
|
|
34392
34415
|
{
|
|
34393
|
-
pattern: /[
|
|
34416
|
+
pattern: /[\u00E4\u00F6\u00FC\u00DF\u1E9E]/i,
|
|
34394
34417
|
averageCharsPerToken: 2.6
|
|
34395
34418
|
},
|
|
34396
34419
|
{
|
|
34397
|
-
pattern: /[
|
|
34420
|
+
pattern: /[\u00E9\u00E8\u00EA\u00EB\u00E0\u00E2\u00EE\u00EF\u00F4\u00FB\u00F9\u00FC\u00FF\u00E7\u0153\u00E6\u00E1\u00ED\u00F3\u00FA\u00F1]/i,
|
|
34398
34421
|
averageCharsPerToken: 3
|
|
34399
34422
|
},
|
|
34400
34423
|
{
|
|
34401
|
-
pattern: /[
|
|
34424
|
+
pattern: /[\u0105\u0107\u0119\u0142\u0144\u00F3\u015B\u017A\u017C\u011B\u0161\u010D\u0159\u017E\u00FD\u016F\u00FA\u010F\u0165\u0148]/i,
|
|
34402
34425
|
averageCharsPerToken: 2.5
|
|
34403
34426
|
},
|
|
34404
34427
|
{
|
|
@@ -34474,7 +34497,7 @@ const OBSERVER_TOOL_ARGUMENT_MAX_DEPTH = 5;
|
|
|
34474
34497
|
const OBSERVER_TOOL_ARGUMENT_MAX_ENTRIES_PER_CONTAINER = 20;
|
|
34475
34498
|
const OBSERVER_TOOL_ARGUMENT_MAX_OUTLINE_ENTRIES = 100;
|
|
34476
34499
|
const OBSERVER_TOOL_ARGUMENT_MAX_PATH_CHARS = 160;
|
|
34477
|
-
function isObjectLike
|
|
34500
|
+
function isObjectLike(value) {
|
|
34478
34501
|
return typeof value === "object" && value !== null;
|
|
34479
34502
|
}
|
|
34480
34503
|
function sanitizeSurrogates(value) {
|
|
@@ -34486,10 +34509,10 @@ function sanitizeSurrogates(value) {
|
|
|
34486
34509
|
if (next >= 56320 && next <= 57343) {
|
|
34487
34510
|
sanitized += value.charAt(index) + value.charAt(index + 1);
|
|
34488
34511
|
index++;
|
|
34489
|
-
} else sanitized += "
|
|
34512
|
+
} else sanitized += "\uFFFD";
|
|
34490
34513
|
continue;
|
|
34491
34514
|
}
|
|
34492
|
-
sanitized += code >= 56320 && code <= 57343 ? "
|
|
34515
|
+
sanitized += code >= 56320 && code <= 57343 ? "\uFFFD" : value[index];
|
|
34493
34516
|
}
|
|
34494
34517
|
return sanitized;
|
|
34495
34518
|
}
|
|
@@ -34511,7 +34534,7 @@ function truncatePath(path) {
|
|
|
34511
34534
|
const headLength = 50;
|
|
34512
34535
|
const tailLength = 60;
|
|
34513
34536
|
const omitted = path.length - headLength - tailLength;
|
|
34514
|
-
return `${safeSlice(path, headLength)}
|
|
34537
|
+
return `${safeSlice(path, headLength)}\u2026[${omitted} chars; ${stablePathDigest(path)}]\u2026${safeTail(path, tailLength)}`;
|
|
34515
34538
|
}
|
|
34516
34539
|
function formatPath(parent, key, isArray) {
|
|
34517
34540
|
if (isArray) return truncatePath(`${parent}[${key}]`);
|
|
@@ -34620,7 +34643,7 @@ function selectOutlineEntries(entries, limits) {
|
|
|
34620
34643
|
const rendered = joinEntries(selected, marker);
|
|
34621
34644
|
if (fits(rendered, limits)) return rendered;
|
|
34622
34645
|
if (fits(marker, limits)) return marker;
|
|
34623
|
-
return fits("
|
|
34646
|
+
return fits("\u2026", limits) ? "\u2026" : "";
|
|
34624
34647
|
}
|
|
34625
34648
|
function indentPreview(value) {
|
|
34626
34649
|
return value.split("\n").map((line) => ` | ${line}`).join("\n");
|
|
@@ -34660,16 +34683,16 @@ function formatToolArgumentsForObserver(value, options) {
|
|
|
34660
34683
|
maxCharacters: options?.maxCharacters ?? Number.POSITIVE_INFINITY
|
|
34661
34684
|
};
|
|
34662
34685
|
if (limits.maxTokens <= 0 || limits.maxCharacters <= 0) return "";
|
|
34663
|
-
if (!isObjectLike
|
|
34686
|
+
if (!isObjectLike(value)) {
|
|
34664
34687
|
if (typeof value !== "string" || value.length <= OBSERVER_TOOL_ARGUMENT_INLINE_STRING_MAX_CHARS) {
|
|
34665
34688
|
const primitive = formatPrimitive(value);
|
|
34666
|
-
return fits(primitive, limits) ? primitive : fits("
|
|
34689
|
+
return fits(primitive, limits) ? primitive : fits("\u2026", limits) ? "\u2026" : "";
|
|
34667
34690
|
}
|
|
34668
34691
|
const summary = `<string, ${value.length} characters; preview size-limited>`;
|
|
34669
34692
|
const rendered = appendWithinBudget(summary, formatPreview("preview", value, limits, summary), limits);
|
|
34670
34693
|
if (rendered) return rendered;
|
|
34671
34694
|
if (fits(summary, limits)) return summary;
|
|
34672
|
-
return fits("
|
|
34695
|
+
return fits("\u2026", limits) ? "\u2026" : "";
|
|
34673
34696
|
}
|
|
34674
34697
|
const outline = [];
|
|
34675
34698
|
const previews = [];
|
|
@@ -34739,7 +34762,7 @@ function formatToolArgumentsForObserver(value, options) {
|
|
|
34739
34762
|
});
|
|
34740
34763
|
continue;
|
|
34741
34764
|
}
|
|
34742
|
-
if (!isObjectLike
|
|
34765
|
+
if (!isObjectLike(entryValue)) {
|
|
34743
34766
|
outline.push({
|
|
34744
34767
|
text: `${path}: ${formatPrimitive(entryValue)}`,
|
|
34745
34768
|
depth: current.depth,
|
|
@@ -34820,28 +34843,22 @@ function formatToolArgumentsForObserver(value, options) {
|
|
|
34820
34843
|
}
|
|
34821
34844
|
const ENCRYPTED_CONTENT_KEY = "encryptedContent";
|
|
34822
34845
|
const ENCRYPTED_CONTENT_REDACTION_THRESHOLD = 256;
|
|
34823
|
-
|
|
34824
|
-
|
|
34825
|
-
|
|
34826
|
-
|
|
34827
|
-
|
|
34828
|
-
|
|
34829
|
-
|
|
34830
|
-
|
|
34831
|
-
seen.set(value, sanitizedArray);
|
|
34832
|
-
for (const item of value) sanitizedArray.push(sanitizeToolResultValue(item, seen));
|
|
34833
|
-
return sanitizedArray;
|
|
34834
|
-
}
|
|
34835
|
-
const sanitizedObject = {};
|
|
34836
|
-
seen.set(value, sanitizedObject);
|
|
34837
|
-
for (const [key, entry] of Object.entries(value)) {
|
|
34838
|
-
if (key === ENCRYPTED_CONTENT_KEY && typeof entry === "string" && entry.length > ENCRYPTED_CONTENT_REDACTION_THRESHOLD) {
|
|
34839
|
-
sanitizedObject[key] = `[stripped encryptedContent: ${entry.length} characters]`;
|
|
34840
|
-
continue;
|
|
34841
|
-
}
|
|
34842
|
-
sanitizedObject[key] = sanitizeToolResultValue(entry, seen);
|
|
34846
|
+
/** The string a boxed `String` serializes to; JSON.stringify unboxes it only after the replacer has run. */
|
|
34847
|
+
function unboxedString(value) {
|
|
34848
|
+
if (typeof value === "string") return value;
|
|
34849
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
34850
|
+
try {
|
|
34851
|
+
String.prototype.valueOf.call(value);
|
|
34852
|
+
} catch {
|
|
34853
|
+
return;
|
|
34843
34854
|
}
|
|
34844
|
-
return
|
|
34855
|
+
return String(value);
|
|
34856
|
+
}
|
|
34857
|
+
/** Redacts long `encryptedContent` strings: opaque provider data that would otherwise dominate the count. */
|
|
34858
|
+
function redactEncryptedContent(key, value) {
|
|
34859
|
+
if (key !== ENCRYPTED_CONTENT_KEY) return value;
|
|
34860
|
+
const text = unboxedString(value);
|
|
34861
|
+
return text !== void 0 && text.length > ENCRYPTED_CONTENT_REDACTION_THRESHOLD ? `[stripped encryptedContent: ${text.length} characters]` : value;
|
|
34845
34862
|
}
|
|
34846
34863
|
/**
|
|
34847
34864
|
* Serializes a tool result without truncating it.
|
|
@@ -34861,14 +34878,20 @@ function serializeToolResultForTokenCounting(value) {
|
|
|
34861
34878
|
function toolErrorTextToString(errorText) {
|
|
34862
34879
|
return errorText == null ? "" : stringifyToolResult(errorText);
|
|
34863
34880
|
}
|
|
34881
|
+
/**
|
|
34882
|
+
* Serializes with `JSON.stringify` itself, the serializer storage uses, so a count of this text describes what
|
|
34883
|
+
* storage holds and a reload reads back (`toJSON()`, boxed primitives, class instances, array indices).
|
|
34884
|
+
*/
|
|
34864
34885
|
function stringifyToolResult(value) {
|
|
34865
34886
|
if (typeof value === "string") return value;
|
|
34866
|
-
|
|
34887
|
+
let json;
|
|
34867
34888
|
try {
|
|
34868
|
-
|
|
34889
|
+
json = JSON.stringify(value, redactEncryptedContent, 2);
|
|
34869
34890
|
} catch {
|
|
34870
|
-
return String(
|
|
34891
|
+
return String(value);
|
|
34871
34892
|
}
|
|
34893
|
+
if (json === void 0) return "";
|
|
34894
|
+
return json.startsWith("\"") ? JSON.parse(json) : json;
|
|
34872
34895
|
}
|
|
34873
34896
|
function resolveToolResultValue(part, invocationResult) {
|
|
34874
34897
|
const mastraMetadata = part?.providerMetadata?.mastra;
|
|
@@ -34882,13 +34905,58 @@ function resolveToolResultValue(part, invocationResult) {
|
|
|
34882
34905
|
usingStoredModelOutput: false
|
|
34883
34906
|
};
|
|
34884
34907
|
}
|
|
34908
|
+
const PREFIX_CHUNK_MIN_LENGTH = 256;
|
|
34909
|
+
function isAsciiAlphanumeric(code) {
|
|
34910
|
+
return code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122;
|
|
34911
|
+
}
|
|
34912
|
+
function isSplitWhitespace(code) {
|
|
34913
|
+
return code === 32 || code === 10 || code === 9 || code === 13;
|
|
34914
|
+
}
|
|
34915
|
+
/**
|
|
34916
|
+
* Returns a function that counts `estimateTokenCount(text.slice(0, end) + suffix)` without rescanning the
|
|
34917
|
+
* whole prefix on every call.
|
|
34918
|
+
*
|
|
34919
|
+
* tokenx splits text into segments on whitespace and punctuation runs and sums a per-segment estimate.
|
|
34920
|
+
* Letters and digits are never separators and whitespace always is, so the position between an ASCII
|
|
34921
|
+
* letter or digit and a following whitespace character is always a segment boundary: the count of any
|
|
34922
|
+
* string that shares the text up to such a position equals the count before it plus the count after it.
|
|
34923
|
+
* The text is cut at those boundaries once, and each call only rescans the chunk it ends in.
|
|
34924
|
+
*/
|
|
34925
|
+
function createPrefixTokenCounter(text) {
|
|
34926
|
+
const boundaries = [0];
|
|
34927
|
+
const tokensBefore = [0];
|
|
34928
|
+
let chunkStart = 0;
|
|
34929
|
+
let runningTokens = 0;
|
|
34930
|
+
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))) {
|
|
34931
|
+
runningTokens += estimateTokenCount(text.slice(chunkStart, i));
|
|
34932
|
+
boundaries.push(i);
|
|
34933
|
+
tokensBefore.push(runningTokens);
|
|
34934
|
+
chunkStart = i;
|
|
34935
|
+
}
|
|
34936
|
+
return (end, suffix = "") => {
|
|
34937
|
+
let low = 0;
|
|
34938
|
+
let high = boundaries.length - 1;
|
|
34939
|
+
while (low < high) {
|
|
34940
|
+
const mid = low + high + 1 >> 1;
|
|
34941
|
+
if (boundaries[mid] <= end) low = mid;
|
|
34942
|
+
else high = mid - 1;
|
|
34943
|
+
}
|
|
34944
|
+
return tokensBefore[low] + estimateTokenCount(text.slice(boundaries[low], end) + suffix);
|
|
34945
|
+
};
|
|
34946
|
+
}
|
|
34885
34947
|
function truncateStringByTokens(text, maxTokens) {
|
|
34886
34948
|
if (!text || maxTokens <= 0) return "";
|
|
34887
|
-
const
|
|
34949
|
+
const countPrefixTokens = createPrefixTokenCounter(text);
|
|
34950
|
+
const totalTokens = countPrefixTokens(text.length);
|
|
34888
34951
|
if (totalTokens <= maxTokens) return text;
|
|
34889
34952
|
const buildCandidate = (sliceEnd) => {
|
|
34890
|
-
const
|
|
34891
|
-
|
|
34953
|
+
const visibleEnd = safeSlice(text, sliceEnd).length;
|
|
34954
|
+
const suffix = `\n... [truncated ~${totalTokens - countPrefixTokens(visibleEnd)} tokens]`;
|
|
34955
|
+
return {
|
|
34956
|
+
visibleEnd,
|
|
34957
|
+
suffix,
|
|
34958
|
+
tokens: countPrefixTokens(visibleEnd, suffix)
|
|
34959
|
+
};
|
|
34892
34960
|
};
|
|
34893
34961
|
let low = 0;
|
|
34894
34962
|
let high = text.length;
|
|
@@ -34896,12 +34964,12 @@ function truncateStringByTokens(text, maxTokens) {
|
|
|
34896
34964
|
while (low <= high) {
|
|
34897
34965
|
const mid = Math.floor((low + high) / 2);
|
|
34898
34966
|
const candidate = buildCandidate(mid);
|
|
34899
|
-
if (
|
|
34967
|
+
if (candidate.tokens <= maxTokens) {
|
|
34900
34968
|
best = candidate;
|
|
34901
34969
|
low = mid + 1;
|
|
34902
34970
|
} else high = mid - 1;
|
|
34903
34971
|
}
|
|
34904
|
-
return best;
|
|
34972
|
+
return text.slice(0, best.visibleEnd) + best.suffix;
|
|
34905
34973
|
}
|
|
34906
34974
|
function formatToolResultForObserver(value, options) {
|
|
34907
34975
|
return truncateStringByTokens(stringifyToolResult(value), options?.maxTokens ?? 5e3);
|
|
@@ -34913,24 +34981,24 @@ function formatToolResultForObserver(value, options) {
|
|
|
34913
34981
|
const OBSERVER_EXTRACTION_INSTRUCTIONS = `CRITICAL: DISTINGUISH USER ASSERTIONS FROM QUESTIONS
|
|
34914
34982
|
|
|
34915
34983
|
When the user TELLS you something about themselves, mark it as an assertion:
|
|
34916
|
-
- "I have two kids"
|
|
34917
|
-
- "I work at Acme Corp"
|
|
34918
|
-
- "I graduated in 2019"
|
|
34984
|
+
- "I have two kids" \u2192 \u{1F534} (14:30) User stated has two kids
|
|
34985
|
+
- "I work at Acme Corp" \u2192 \u{1F534} (14:31) User stated works at Acme Corp
|
|
34986
|
+
- "I graduated in 2019" \u2192 \u{1F534} (14:32) User stated graduated in 2019
|
|
34919
34987
|
|
|
34920
34988
|
When the user ASKS about something, mark it as a question/request:
|
|
34921
|
-
- "Can you help me with X?"
|
|
34922
|
-
- "What's the best way to do Y?"
|
|
34989
|
+
- "Can you help me with X?" \u2192 \u{1F534} (15:00) User asked help with X
|
|
34990
|
+
- "What's the best way to do Y?" \u2192 \u{1F534} (15:01) User asked best way to do Y
|
|
34923
34991
|
|
|
34924
34992
|
Distinguish between QUESTIONS and STATEMENTS OF INTENT:
|
|
34925
|
-
- "Can you recommend..."
|
|
34926
|
-
- "I'm looking forward to [doing X]"
|
|
34927
|
-
- "I need to [do X]"
|
|
34993
|
+
- "Can you recommend..." \u2192 Question (extract as "User asked...")
|
|
34994
|
+
- "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)")
|
|
34995
|
+
- "I need to [do X]" \u2192 Statement of intent (extract as "User stated they need to [do X] (again, add date if mentioned)")
|
|
34928
34996
|
|
|
34929
34997
|
STATE CHANGES AND UPDATES:
|
|
34930
34998
|
When a user indicates they are changing something, frame it as a state change that supersedes previous information:
|
|
34931
|
-
- "I'm going to start doing X instead of Y"
|
|
34932
|
-
- "I'm switching from A to B"
|
|
34933
|
-
- "I moved my stuff to the new place"
|
|
34999
|
+
- "I'm going to start doing X instead of Y" \u2192 "User will start doing X (changing from Y)"
|
|
35000
|
+
- "I'm switching from A to B" \u2192 "User is switching from A to B"
|
|
35001
|
+
- "I moved my stuff to the new place" \u2192 "User moved their stuff to the new place (no longer at previous location)"
|
|
34934
35002
|
|
|
34935
35003
|
If the new state contradicts or updates previous information, make that explicit:
|
|
34936
35004
|
- BAD: "User plans to use the new method"
|
|
@@ -35021,11 +35089,11 @@ BAD: User got something.
|
|
|
35021
35089
|
GOOD: User purchased / received / was given something. (be specific)
|
|
35022
35090
|
|
|
35023
35091
|
Common clarifications:
|
|
35024
|
-
- "getting" something regularly
|
|
35025
|
-
- "getting" something once
|
|
35026
|
-
- "got"
|
|
35027
|
-
- "signed up"
|
|
35028
|
-
- "stopped getting"
|
|
35092
|
+
- "getting" something regularly \u2192 "subscribed to" or "enrolled in"
|
|
35093
|
+
- "getting" something once \u2192 "purchased" or "acquired"
|
|
35094
|
+
- "got" \u2192 "purchased", "received as gift", "was given", "picked up"
|
|
35095
|
+
- "signed up" \u2192 "enrolled in", "registered for", "subscribed to"
|
|
35096
|
+
- "stopped getting" \u2192 "canceled", "unsubscribed from", "discontinued"
|
|
35029
35097
|
|
|
35030
35098
|
When the assistant interprets or confirms the user's vague language, prefer the assistant's precise terminology.
|
|
35031
35099
|
|
|
@@ -35110,16 +35178,16 @@ AVOIDING REPETITIVE OBSERVATIONS:
|
|
|
35110
35178
|
- Do NOT repeat the same observation across multiple turns if there is no new information.
|
|
35111
35179
|
- When the agent performs repeated similar actions (e.g., browsing files, running the same tool type multiple times), group them into a single parent observation with sub-bullets for each new result.
|
|
35112
35180
|
|
|
35113
|
-
Example
|
|
35114
|
-
*
|
|
35115
|
-
*
|
|
35116
|
-
*
|
|
35181
|
+
Example \u2014 BAD (repetitive):
|
|
35182
|
+
* \u{1F7E1} (14:30) Agent used view tool on src/auth.ts
|
|
35183
|
+
* \u{1F7E1} (14:31) Agent used view tool on src/users.ts
|
|
35184
|
+
* \u{1F7E1} (14:32) Agent used view tool on src/routes.ts
|
|
35117
35185
|
|
|
35118
|
-
Example
|
|
35119
|
-
*
|
|
35120
|
-
* -> viewed src/auth.ts
|
|
35121
|
-
* -> viewed src/users.ts
|
|
35122
|
-
* -> viewed src/routes.ts
|
|
35186
|
+
Example \u2014 GOOD (grouped):
|
|
35187
|
+
* \u{1F7E1} (14:30) Agent browsed source files for auth flow
|
|
35188
|
+
* -> viewed src/auth.ts \u2014 found token validation logic
|
|
35189
|
+
* -> viewed src/users.ts \u2014 found user lookup by email
|
|
35190
|
+
* -> viewed src/routes.ts \u2014 found middleware chain
|
|
35123
35191
|
|
|
35124
35192
|
Only add a new observation for a repeated action if the NEW result changes the picture.
|
|
35125
35193
|
|
|
@@ -35132,29 +35200,29 @@ COMPLETION TRACKING:
|
|
|
35132
35200
|
Completion observations are not just summaries. They are explicit memory signals to the assistant that a task, question, or subtask has been resolved.
|
|
35133
35201
|
Without clear completion markers, the assistant may forget that work is already finished and may repeat, reopen, or continue an already-completed task.
|
|
35134
35202
|
|
|
35135
|
-
Use
|
|
35203
|
+
Use \u2705 to answer: "What exactly is now done?"
|
|
35136
35204
|
Choose completion observations that help the assistant know what is finished and should not be reworked unless new information appears.
|
|
35137
35205
|
|
|
35138
|
-
Use
|
|
35206
|
+
Use \u2705 when:
|
|
35139
35207
|
- The user explicitly confirms something worked or was answered ("thanks, that fixed it", "got it", "perfect")
|
|
35140
35208
|
- The assistant provided a definitive, complete answer to a factual question and the user moved on
|
|
35141
35209
|
- A multi-step task reached its stated goal
|
|
35142
35210
|
- The user acknowledged receipt of requested information
|
|
35143
35211
|
- A concrete subtask, fix, deliverable, or implementation step became complete during ongoing work
|
|
35144
35212
|
|
|
35145
|
-
Do NOT use
|
|
35146
|
-
- The assistant merely responded
|
|
35213
|
+
Do NOT use \u2705 when:
|
|
35214
|
+
- The assistant merely responded \u2014 the user might follow up with corrections
|
|
35147
35215
|
- The topic is paused but not resolved ("I'll try that later")
|
|
35148
35216
|
- The user's reaction is ambiguous
|
|
35149
35217
|
|
|
35150
35218
|
FORMAT:
|
|
35151
35219
|
As a sub-bullet under the related observation group:
|
|
35152
|
-
*
|
|
35220
|
+
* \u{1F534} (14:30) User asked how to configure auth middleware
|
|
35153
35221
|
* -> Agent explained JWT setup with code example
|
|
35154
|
-
*
|
|
35222
|
+
* \u2705 User confirmed auth is working
|
|
35155
35223
|
|
|
35156
35224
|
Or as a standalone observation when closing out a broader task:
|
|
35157
|
-
*
|
|
35225
|
+
* \u2705 (14:45) Auth configuration task completed \u2014 user confirmed middleware is working
|
|
35158
35226
|
|
|
35159
35227
|
Completion observations should be terse but specific about WHAT was completed.
|
|
35160
35228
|
Prefer concrete resolved outcomes over abstract workflow status so the assistant remembers what is already done.`;
|
|
@@ -35171,28 +35239,28 @@ buildObserverOutputFormat();
|
|
|
35171
35239
|
*/
|
|
35172
35240
|
function buildObserverOutputFormat(extractors) {
|
|
35173
35241
|
return `Use priority levels:
|
|
35174
|
-
-
|
|
35175
|
-
-
|
|
35176
|
-
-
|
|
35177
|
-
-
|
|
35242
|
+
- \u{1F534} High: explicit user facts, preferences, unresolved goals, critical context
|
|
35243
|
+
- \u{1F7E1} Medium: project details, learned information, tool results
|
|
35244
|
+
- \u{1F7E2} Low: minor details, uncertain observations
|
|
35245
|
+
- \u2705 Completed: concrete task finished, question answered, issue resolved, goal achieved, or subtask completed in a way that helps the assistant know it is done
|
|
35178
35246
|
|
|
35179
35247
|
Group related observations (like tool sequences) by indenting:
|
|
35180
|
-
*
|
|
35248
|
+
* \u{1F534} (14:33) Agent debugging auth issue
|
|
35181
35249
|
* -> ran git status, found 3 modified files
|
|
35182
35250
|
* -> viewed auth.ts:45-60, found missing null check
|
|
35183
35251
|
* -> applied fix, tests now pass
|
|
35184
|
-
*
|
|
35252
|
+
* \u2705 Tests passing, auth issue resolved
|
|
35185
35253
|
|
|
35186
35254
|
Group observations by date. Within a date, list observations in the order the events happened (not by importance), each with 24-hour time.
|
|
35187
35255
|
|
|
35188
35256
|
<observations>
|
|
35189
35257
|
Date: Dec 4, 2025
|
|
35190
|
-
*
|
|
35191
|
-
*
|
|
35192
|
-
*
|
|
35258
|
+
* \u{1F534} (14:30) User prefers direct answers
|
|
35259
|
+
* \u{1F534} (14:31) Working on feature X
|
|
35260
|
+
* \u{1F7E1} (14:32) User might prefer dark mode
|
|
35193
35261
|
|
|
35194
35262
|
Date: Dec 5, 2025
|
|
35195
|
-
*
|
|
35263
|
+
* \u{1F534} (09:15) Continued work on feature X
|
|
35196
35264
|
</observations>
|
|
35197
35265
|
|
|
35198
35266
|
${buildExtractorOutputSections(extractors ?? []) || (extractors === void 0 ? `
|
|
@@ -35222,9 +35290,9 @@ const OBSERVER_GUIDELINES = `- Be specific enough for the assistant to act on
|
|
|
35222
35290
|
- If the agent calls tools, observe what was called, why, and what was learned
|
|
35223
35291
|
- When observing files with line numbers, include the line number if useful
|
|
35224
35292
|
- If the agent provides a detailed response, observe the contents so it could be repeated
|
|
35225
|
-
- Make sure you start each observation with a priority emoji (
|
|
35226
|
-
- Capture the user's words closely
|
|
35227
|
-
- Treat
|
|
35293
|
+
- Make sure you start each observation with a priority emoji (\u{1F534}, \u{1F7E1}, \u{1F7E2}) or a completion marker (\u2705)
|
|
35294
|
+
- 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}
|
|
35295
|
+
- Treat \u2705 as a memory signal that tells the assistant something is finished and should not be repeated unless new information changes it
|
|
35228
35296
|
- Make completion observations answer "What exactly is now done?"
|
|
35229
35297
|
- Prefer concrete resolved outcomes over meta-level workflow or bookkeeping updates
|
|
35230
35298
|
- When multiple concrete things were completed, capture the concrete completed work rather than collapsing it into a vague progress summary
|
|
@@ -35278,8 +35346,8 @@ For multi-thread output, wrap each thread's observations like this:
|
|
|
35278
35346
|
<observations>
|
|
35279
35347
|
<thread id="thread_id_1">
|
|
35280
35348
|
Date: Dec 4, 2025
|
|
35281
|
-
*
|
|
35282
|
-
*
|
|
35349
|
+
* \u{1F534} (14:30) User prefers direct answers
|
|
35350
|
+
* \u{1F534} (14:31) Working on feature X${currentTaskEnabled ? `
|
|
35283
35351
|
|
|
35284
35352
|
<current-task>
|
|
35285
35353
|
What the agent is currently working on in this thread
|
|
@@ -35292,7 +35360,7 @@ Hint for the agent's next message in this thread
|
|
|
35292
35360
|
|
|
35293
35361
|
<thread id="thread_id_2">
|
|
35294
35362
|
Date: Dec 5, 2025
|
|
35295
|
-
*
|
|
35363
|
+
* \u{1F534} (09:15) User asked about deployment${currentTaskEnabled ? `
|
|
35296
35364
|
|
|
35297
35365
|
<current-task>
|
|
35298
35366
|
Current task for this thread
|
|
@@ -36123,7 +36191,7 @@ function sanitizeObservationLines(observations) {
|
|
|
36123
36191
|
const lines = observations.split("\n");
|
|
36124
36192
|
let changed = false;
|
|
36125
36193
|
for (let i = 0; i < lines.length; i++) if (lines[i].length > MAX_OBSERVATION_LINE_CHARS) {
|
|
36126
|
-
lines[i] = safeSlice(lines[i], MAX_OBSERVATION_LINE_CHARS) + "
|
|
36194
|
+
lines[i] = safeSlice(lines[i], MAX_OBSERVATION_LINE_CHARS) + " \u2026 [truncated]";
|
|
36127
36195
|
changed = true;
|
|
36128
36196
|
}
|
|
36129
36197
|
return changed ? lines.join("\n") : observations;
|
|
@@ -36321,8 +36389,8 @@ function describeDegenerateOutput(text, snippetChars = 400) {
|
|
|
36321
36389
|
*/
|
|
36322
36390
|
function optimizeObservationsForContext(observations) {
|
|
36323
36391
|
let optimized = stripEphemeralAnchorIds(observations);
|
|
36324
|
-
optimized = optimized.replace(
|
|
36325
|
-
optimized = optimized.replace(
|
|
36392
|
+
optimized = optimized.replace(/\uD83D\uDFE1\s*/g, "");
|
|
36393
|
+
optimized = optimized.replace(/\uD83D\uDFE2\s*/g, "");
|
|
36326
36394
|
optimized = optimized.replace(/\s*->\s*/g, " ");
|
|
36327
36395
|
optimized = optimized.replace(/ +/g, " ");
|
|
36328
36396
|
optimized = optimized.replace(/\n{3,}/g, "\n\n");
|
|
@@ -37117,9 +37185,24 @@ function mergeCacheEntry(cache, key, entry) {
|
|
|
37117
37185
|
function getPartCacheEntry(part, key) {
|
|
37118
37186
|
return getCacheEntry(getPartMastraMetadata(part)?.tokenEstimate, key);
|
|
37119
37187
|
}
|
|
37188
|
+
/**
|
|
37189
|
+
* Parts this process gave a new stored count. A part loaded from storage with its count is never in here,
|
|
37190
|
+
* so a message holding one of these parts has a count storage does not have yet.
|
|
37191
|
+
*/
|
|
37192
|
+
const partsWithUnsavedCount = /* @__PURE__ */ new WeakSet();
|
|
37193
|
+
/** Whether `part` gained a stored count in this process that has not been handed to a save yet. */
|
|
37194
|
+
function hasUnsavedTokenEstimate(part) {
|
|
37195
|
+
return typeof part === "object" && part !== null && partsWithUnsavedCount.has(part);
|
|
37196
|
+
}
|
|
37197
|
+
/** Note that `part`'s count is on its way to storage, so later steps do not save it again. */
|
|
37198
|
+
function markTokenEstimateSaved(part) {
|
|
37199
|
+
if (typeof part === "object" && part !== null) partsWithUnsavedCount.delete(part);
|
|
37200
|
+
}
|
|
37201
|
+
const partCountMemo = /* @__PURE__ */ new WeakMap();
|
|
37120
37202
|
function setPartCacheEntry(part, key, entry) {
|
|
37121
37203
|
const mastraMetadata = ensurePartMastraMetadata(part);
|
|
37122
37204
|
mastraMetadata.tokenEstimate = mergeCacheEntry(mastraMetadata.tokenEstimate, key, entry);
|
|
37205
|
+
partsWithUnsavedCount.add(part);
|
|
37123
37206
|
}
|
|
37124
37207
|
/**
|
|
37125
37208
|
* Extracts a caller-supplied token estimate stamped on a part via
|
|
@@ -37278,7 +37361,7 @@ async function resolveImageDimensionsAsync(part) {
|
|
|
37278
37361
|
const url = resolveHttpAssetUrl(getObjectValue(part, "image") ?? getObjectValue(part, "data"));
|
|
37279
37362
|
if (!url) return existing;
|
|
37280
37363
|
try {
|
|
37281
|
-
const probeImageSize = (await Promise.resolve().then(() => /* @__PURE__ */ require_rolldown_runtime.__toESM(require("./probe-image-size-
|
|
37364
|
+
const probeImageSize = (await Promise.resolve().then(() => /* @__PURE__ */ require_rolldown_runtime.__toESM(require("./probe-image-size-ntJyQKKB.cjs").default, 1))).default;
|
|
37282
37365
|
const probed = await probeImageSize(url, {
|
|
37283
37366
|
open_timeout: REMOTE_IMAGE_PROBE_TIMEOUT_MS,
|
|
37284
37367
|
response_timeout: REMOTE_IMAGE_PROBE_TIMEOUT_MS,
|
|
@@ -37813,14 +37896,19 @@ async function fetchGoogleAttachmentTokenEstimate(modelId, part) {
|
|
|
37813
37896
|
* undercounted as generic JSON blobs.
|
|
37814
37897
|
*/
|
|
37815
37898
|
var TokenCounter = class TokenCounter {
|
|
37816
|
-
|
|
37899
|
+
/**
|
|
37900
|
+
* Stored counts belong to the stock estimator. A subclass or instance that overrides `countString`
|
|
37901
|
+
* reads and writes its own namespace, so it never reuses a count the stock estimator saved.
|
|
37902
|
+
*/
|
|
37903
|
+
get cacheSource() {
|
|
37904
|
+
return this.countString === TokenCounter.prototype.countString ? `v${TOKEN_ESTIMATE_CACHE_VERSION}:${resolveEstimatorId()}` : `v${TOKEN_ESTIMATE_CACHE_VERSION}:custom`;
|
|
37905
|
+
}
|
|
37817
37906
|
defaultModelContext;
|
|
37818
37907
|
inFlightAttachmentCounts = /* @__PURE__ */ new Map();
|
|
37819
37908
|
multimodalToolResultCounts = /* @__PURE__ */ new WeakMap();
|
|
37820
37909
|
static TOKENS_PER_MESSAGE = 3.8;
|
|
37821
37910
|
static TOKENS_PER_CONVERSATION = 24;
|
|
37822
37911
|
constructor(options) {
|
|
37823
|
-
this.cacheSource = `v${TOKEN_ESTIMATE_CACHE_VERSION}:${resolveEstimatorId()}`;
|
|
37824
37912
|
this.defaultModelContext = parseModelContext(options?.model);
|
|
37825
37913
|
}
|
|
37826
37914
|
runWithModelContext(model, fn) {
|
|
@@ -37851,6 +37939,28 @@ var TokenCounter = class TokenCounter {
|
|
|
37851
37939
|
});
|
|
37852
37940
|
return tokens;
|
|
37853
37941
|
}
|
|
37942
|
+
/**
|
|
37943
|
+
* Count one content-only piece of a part (its text, a tool's args or result) the same way as
|
|
37944
|
+
* {@link readOrPersistPartEstimate}: a stored count is reused only when its content hash matches.
|
|
37945
|
+
* `refs` are the values the payload is built from. While the same part object still holds the same
|
|
37946
|
+
* refs, the count from the last call is returned without serializing or hashing again, so a part
|
|
37947
|
+
* counted by `getStatus` and then by the next step is hashed once per process.
|
|
37948
|
+
* Only string refs are memoized (object payloads are hashed every time, since they can change in place).
|
|
37949
|
+
*/
|
|
37950
|
+
readOrPersistMemoizedPartEstimate(part, kind, refs, getPayload) {
|
|
37951
|
+
if (!refs.every((ref) => typeof ref === "string")) return this.readOrPersistPartEstimate(part, kind, getPayload());
|
|
37952
|
+
let byKind = partCountMemo.get(part);
|
|
37953
|
+
const memo = byKind?.get(kind);
|
|
37954
|
+
if (memo && memo.owner === this && memo.refs.length === refs.length && memo.refs.every((ref, i) => ref === refs[i])) return memo.tokens;
|
|
37955
|
+
const tokens = this.readOrPersistPartEstimate(part, kind, getPayload());
|
|
37956
|
+
if (!byKind) partCountMemo.set(part, byKind = /* @__PURE__ */ new Map());
|
|
37957
|
+
byKind.set(kind, {
|
|
37958
|
+
owner: this,
|
|
37959
|
+
refs,
|
|
37960
|
+
tokens
|
|
37961
|
+
});
|
|
37962
|
+
return tokens;
|
|
37963
|
+
}
|
|
37854
37964
|
readOrPersistFixedPartEstimate(part, kind, payload, tokens) {
|
|
37855
37965
|
const key = buildEstimateKey(kind, payload);
|
|
37856
37966
|
const cached = getPartCacheEntry(part, key);
|
|
@@ -38201,18 +38311,23 @@ var TokenCounter = class TokenCounter {
|
|
|
38201
38311
|
/**
|
|
38202
38312
|
* Count the name and the arguments of a tool call. Every state before the tool produces an
|
|
38203
38313
|
* output holds the same call signature in the context window, so all of those states share
|
|
38204
|
-
* these cache kinds
|
|
38205
|
-
*
|
|
38314
|
+
* these cache kinds, and the estimate stays warm while the invocation moves from one state to
|
|
38315
|
+
* the next. Name and args don't change across those states once the call stops streaming.
|
|
38206
38316
|
*/
|
|
38207
38317
|
countToolCallSignature(part, invocation) {
|
|
38208
38318
|
let tokens = 0;
|
|
38209
38319
|
let overheadDelta = 0;
|
|
38210
|
-
|
|
38320
|
+
const storable = invocation.state !== "partial-call";
|
|
38321
|
+
const count = (kind, ref, getPayload) => storable ? this.readOrPersistMemoizedPartEstimate(part, kind, [ref], getPayload) : this.readOrPersistPartEstimate(part, kind, getPayload());
|
|
38322
|
+
if (invocation.toolName) {
|
|
38323
|
+
const toolName = invocation.toolName;
|
|
38324
|
+
tokens += count("tool-call-name", toolName, () => toolName);
|
|
38325
|
+
}
|
|
38211
38326
|
if (invocation.args !== void 0) {
|
|
38212
|
-
|
|
38327
|
+
const args = invocation.args;
|
|
38328
|
+
if (typeof args === "string") tokens += count("tool-call-args", args, () => args);
|
|
38213
38329
|
else {
|
|
38214
|
-
|
|
38215
|
-
tokens += this.readOrPersistPartEstimate(part, "tool-call-args-json", argsJson);
|
|
38330
|
+
tokens += count("tool-call-args-json", args, () => JSON.stringify(args));
|
|
38216
38331
|
overheadDelta -= 12;
|
|
38217
38332
|
}
|
|
38218
38333
|
}
|
|
@@ -38224,11 +38339,14 @@ var TokenCounter = class TokenCounter {
|
|
|
38224
38339
|
countNonAttachmentPart(part) {
|
|
38225
38340
|
let overheadDelta = 0;
|
|
38226
38341
|
let extraMessageDelta = 0;
|
|
38227
|
-
if (part.type === "text")
|
|
38228
|
-
|
|
38229
|
-
|
|
38230
|
-
|
|
38231
|
-
|
|
38342
|
+
if (part.type === "text") {
|
|
38343
|
+
const text = part.text;
|
|
38344
|
+
return {
|
|
38345
|
+
tokens: this.readOrPersistMemoizedPartEstimate(part, "text", [text], () => text),
|
|
38346
|
+
overheadDelta,
|
|
38347
|
+
extraMessageDelta
|
|
38348
|
+
};
|
|
38349
|
+
}
|
|
38232
38350
|
if (part.type === "tool-invocation") {
|
|
38233
38351
|
const invocation = part.toolInvocation;
|
|
38234
38352
|
const state = invocation.state;
|
|
@@ -38247,7 +38365,7 @@ var TokenCounter = class TokenCounter {
|
|
|
38247
38365
|
tokens += signature.tokens;
|
|
38248
38366
|
overheadDelta += signature.overheadDelta;
|
|
38249
38367
|
const reason = invocation.approval?.reason;
|
|
38250
|
-
if (reason) tokens += this.
|
|
38368
|
+
if (reason) tokens += this.readOrPersistMemoizedPartEstimate(part, "tool-approval-reason", [reason], () => reason);
|
|
38251
38369
|
return {
|
|
38252
38370
|
tokens,
|
|
38253
38371
|
overheadDelta,
|
|
@@ -38263,15 +38381,12 @@ var TokenCounter = class TokenCounter {
|
|
|
38263
38381
|
if (resultForCounting !== void 0 && (typeof resultForCounting !== "string" || resultForCounting.trim().length > 0)) {
|
|
38264
38382
|
const contentTokens = this.countMultimodalToolResultContent(part, resultForCounting);
|
|
38265
38383
|
if (contentTokens !== void 0) tokens += contentTokens;
|
|
38266
|
-
else
|
|
38267
|
-
const formattedResult = serializeToolResultForTokenCounting(resultForCounting);
|
|
38268
|
-
tokens += this.readOrPersistPartEstimate(part, usingStoredModelOutput ? "tool-result-model-output-json" : "tool-result-json", formattedResult);
|
|
38269
|
-
}
|
|
38384
|
+
else tokens += this.readOrPersistMemoizedPartEstimate(part, usingStoredModelOutput ? "tool-result-model-output-json" : "tool-result-json", [resultForCounting], () => serializeToolResultForTokenCounting(resultForCounting));
|
|
38270
38385
|
if (typeof resultForCounting !== "string") overheadDelta -= 12;
|
|
38271
38386
|
} else {
|
|
38272
38387
|
const errorText = toolErrorTextToString(invocation.errorText);
|
|
38273
38388
|
const fallback = invocation.isError ? errorText.trim() ? errorText : "Tool execution failed" : "[empty result]";
|
|
38274
|
-
tokens += this.
|
|
38389
|
+
tokens += this.readOrPersistMemoizedPartEstimate(part, invocation.isError ? "tool-result-error" : "tool-result-json", [fallback], () => fallback);
|
|
38275
38390
|
}
|
|
38276
38391
|
return {
|
|
38277
38392
|
tokens,
|
|
@@ -38285,7 +38400,7 @@ var TokenCounter = class TokenCounter {
|
|
|
38285
38400
|
tokens += signature.tokens;
|
|
38286
38401
|
overheadDelta += signature.overheadDelta;
|
|
38287
38402
|
const reason = invocation.approval?.reason?.trim() ? invocation.approval.reason : "Tool call was not approved by the user";
|
|
38288
|
-
tokens += this.
|
|
38403
|
+
tokens += this.readOrPersistMemoizedPartEstimate(part, "tool-result-denied", [reason], () => reason);
|
|
38289
38404
|
return {
|
|
38290
38405
|
tokens,
|
|
38291
38406
|
overheadDelta,
|
|
@@ -38299,7 +38414,7 @@ var TokenCounter = class TokenCounter {
|
|
|
38299
38414
|
overheadDelta += signature.overheadDelta;
|
|
38300
38415
|
const errorText = toolErrorTextToString(invocation.errorText);
|
|
38301
38416
|
const errorMessage = errorText.trim() ? errorText : "Tool execution failed";
|
|
38302
|
-
tokens += this.
|
|
38417
|
+
tokens += this.readOrPersistMemoizedPartEstimate(part, "tool-result-error", [errorMessage], () => errorMessage);
|
|
38303
38418
|
return {
|
|
38304
38419
|
tokens,
|
|
38305
38420
|
overheadDelta,
|
|
@@ -38312,6 +38427,11 @@ var TokenCounter = class TokenCounter {
|
|
|
38312
38427
|
overheadDelta,
|
|
38313
38428
|
extraMessageDelta
|
|
38314
38429
|
};
|
|
38430
|
+
if (part.type === "step-start") return {
|
|
38431
|
+
tokens: 0,
|
|
38432
|
+
overheadDelta,
|
|
38433
|
+
extraMessageDelta
|
|
38434
|
+
};
|
|
38315
38435
|
if (part.type === "reasoning") return {
|
|
38316
38436
|
tokens: 0,
|
|
38317
38437
|
overheadDelta,
|
|
@@ -38600,8 +38720,8 @@ const updateWorkingMemoryTool = (memoryConfig) => {
|
|
|
38600
38720
|
}
|
|
38601
38721
|
const usesMergeSemantics = Boolean(schema);
|
|
38602
38722
|
const useStateSignals = memoryConfig?.workingMemory?.useStateSignals === true;
|
|
38603
|
-
const stateSignalsPreamble = `The current working memory state is delivered to you each turn by the system inside a <working-memory>...</working-memory> block. That block is system-emitted state, NOT something the user typed
|
|
38604
|
-
const description = schema ? useStateSignals ? `${stateSignalsPreamble} Data is merged with existing memory
|
|
38723
|
+
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.`;
|
|
38724
|
+
const description = schema ? useStateSignals ? `${stateSignalsPreamble} Data is merged with existing memory \u2014 only include fields you want to add or update.` : `Update the working memory with new information. Data is merged with existing memory - only include fields you want to add or update. To preserve existing data, omit the field entirely. Arrays are replaced entirely when provided, so pass the complete array or omit it to keep the existing values.` : useStateSignals ? `${stateSignalsPreamble} Pass the full updated Markdown blob as a string in the memory field.` : `Update the working memory with new information. Any data not included will be overwritten. Always pass data as string to the memory field. Never pass an object.`;
|
|
38605
38725
|
return (0, _mastra_core_tools.createTool)({
|
|
38606
38726
|
id: "update-working-memory",
|
|
38607
38727
|
description,
|
|
@@ -39611,8 +39731,8 @@ async function pageGroups({ om, threadId, resourceId, groupId, recordId, directi
|
|
|
39611
39731
|
})).count > 0;
|
|
39612
39732
|
const hasLater = direction === "before" || hasMore;
|
|
39613
39733
|
const newer = hasLater ? null : await newerMessagesNote(page.at(-1).group, countNewerMessages, pagingThreadId);
|
|
39614
|
-
text.unshift(hasEarlier ?
|
|
39615
|
-
text.push(hasLater ?
|
|
39734
|
+
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");
|
|
39735
|
+
text.push(hasLater ? `\u2014 Browse later: ${pagingCall(page.at(-1).group.id, "after", pagingThreadId, page.at(-1).record.id)} \u2014` : newer ? `\u2014 End of observation history for this thread. ${newer} \u2014` : "\u2014 End of retained observation history for this thread. \u2014");
|
|
39616
39736
|
text.unshift(`### Observation page\nThread: ${threadTitle || "(untitled)"}\nShowing ${page.length} groups ${requestedDirection === void 0 ? "starting at" : `strictly ${direction}`} \`${groupId}\` (oldest first).`);
|
|
39617
39737
|
return {
|
|
39618
39738
|
results: text.join("\n\n"),
|
|
@@ -39798,7 +39918,7 @@ async function listThreadsForResource({ memory, resourceId, currentThreadId, pag
|
|
|
39798
39918
|
const title = thread.title || "(untitled)";
|
|
39799
39919
|
const updated = formatTimestamp(thread.updatedAt);
|
|
39800
39920
|
const created = formatTimestamp(thread.createdAt);
|
|
39801
|
-
const marker = isCurrent ? "
|
|
39921
|
+
const marker = isCurrent ? " \u2190 current" : "";
|
|
39802
39922
|
lines.push(`- **${title}**${marker}`);
|
|
39803
39923
|
lines.push(` id: ${thread.id}`);
|
|
39804
39924
|
lines.push(` updated: ${updated} | created: ${created}`);
|
|
@@ -39977,7 +40097,7 @@ async function searchMessagesForResource({ memory, om, resourceId, currentThread
|
|
|
39977
40097
|
const groupLine = match.groupId ? `- observation group: ${groupCursor(match.groupId, match.recordId)}` : void 0;
|
|
39978
40098
|
const scoreLine = `- score: ${match.score.toFixed(2)}`;
|
|
39979
40099
|
const prev = i > 0 ? ordered[i - 1].match : void 0;
|
|
39980
|
-
if (om && prev?.groupId && match.groupId && prev.threadId === match.threadId) sections.push(
|
|
40100
|
+
if (om && prev?.groupId && match.groupId && prev.threadId === match.threadId) sections.push(`\u2014 Observation groups may be hidden between these results; continue with ${pagingCall(prev.groupId, "after", includeThreadId ? prev.threadId : void 0, prev.recordId)} \u2014`);
|
|
39981
40101
|
if (suppression) {
|
|
39982
40102
|
sections.push(`${groupLine}\n thread: ${match.threadId}; ${suppression}`);
|
|
39983
40103
|
continue;
|
|
@@ -40532,7 +40652,7 @@ async function recallAttachmentView({ memory, threadId, resourceId, cursor, part
|
|
|
40532
40652
|
const partType = rawPart?.type;
|
|
40533
40653
|
if (!rawPart || partType !== "image" && partType !== "file") return { messages: `Part ${partIndex} of message ${cursor} is ${rawPart ? `a ${partType ?? "unknown"}-type part` : "missing"}, not an attachment. Call recall with the same cursor and partIndex without viewAttachment to read it.` };
|
|
40534
40654
|
const resolvedAttachment = resolveViewableAttachment(rawPart);
|
|
40535
|
-
if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)}
|
|
40655
|
+
if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)} \u2014 ${resolvedAttachment.note}` };
|
|
40536
40656
|
return { content: [{
|
|
40537
40657
|
type: "text",
|
|
40538
40658
|
text: formatAttachmentPart(partType, rawPart)
|
|
@@ -40935,7 +41055,7 @@ const recallTool = (_memoryConfig, options) => {
|
|
|
40935
41055
|
if (!thread) return { error: "Could not resolve current thread." };
|
|
40936
41056
|
if (isResourceScope && resourceId && thread.resourceId !== resourceId) throw new Error("Thread does not belong to the active resource");
|
|
40937
41057
|
return {
|
|
40938
|
-
threads: `- **${thread.title || "(untitled)"}**
|
|
41058
|
+
threads: `- **${thread.title || "(untitled)"}** \u2190 current\n id: ${thread.id}\n updated: ${formatTimestamp(thread.updatedAt)} | created: ${formatTimestamp(thread.createdAt)}`,
|
|
40939
41059
|
count: 1,
|
|
40940
41060
|
page: 0,
|
|
40941
41061
|
hasMore: false
|
|
@@ -41686,9 +41806,10 @@ const suggestedResponseInstructions = `Hint for the agent's immediate next messa
|
|
|
41686
41806
|
- "The assistant should wait for the user to respond before continuing."
|
|
41687
41807
|
- Call the view tool on src/example.ts to continue debugging.`;
|
|
41688
41808
|
const threadTitleInstructions = `A short, noun-phrase title for this conversation (2-5 words). Examples:
|
|
41689
|
-
- "Auth bug fix"
|
|
41690
|
-
- "Dark mode toggle"
|
|
41691
|
-
- "Deployment pipeline setup"
|
|
41809
|
+
- "Auth bug fix" \u2014 not "Fixing the auth bug"
|
|
41810
|
+
- "Dark mode toggle" \u2014 not "User wants dark mode toggle added"
|
|
41811
|
+
- "Deployment pipeline setup" \u2014 not "Setting up deployment pipeline for project"
|
|
41812
|
+
Write the title in the same language the user's messages are written in.
|
|
41692
41813
|
Only update when the topic meaningfully changes.`;
|
|
41693
41814
|
function createCurrentTaskExtractor() {
|
|
41694
41815
|
return new Extractor({
|
|
@@ -42758,7 +42879,7 @@ var SyncObservationStrategy = class extends ObservationStrategy {
|
|
|
42758
42879
|
failures: result.extractionFailures,
|
|
42759
42880
|
previousValues: this.priorExtractedValues,
|
|
42760
42881
|
rawObservations: result.observations,
|
|
42761
|
-
recentMessages: formatMessagesForObserver(this.opts.messages, {
|
|
42882
|
+
recentMessages: () => formatMessagesForObserver(this.opts.messages, {
|
|
42762
42883
|
maxPartLength: 500,
|
|
42763
42884
|
timeZone: this.opts.record.observedTimezone
|
|
42764
42885
|
}),
|
|
@@ -42982,7 +43103,7 @@ var AsyncBufferObservationStrategy = class extends ObservationStrategy {
|
|
|
42982
43103
|
failures: result.extractionFailures,
|
|
42983
43104
|
previousValues: this.priorExtractedValues,
|
|
42984
43105
|
rawObservations: result.observations,
|
|
42985
|
-
recentMessages: formatMessagesForObserver(messages, {
|
|
43106
|
+
recentMessages: () => formatMessagesForObserver(messages, {
|
|
42986
43107
|
maxPartLength: 500,
|
|
42987
43108
|
timeZone: this.opts.record.observedTimezone
|
|
42988
43109
|
}),
|
|
@@ -43411,7 +43532,7 @@ var ResourceScopedObservationStrategy = class extends ObservationStrategy {
|
|
|
43411
43532
|
failures: result.extractionFailures,
|
|
43412
43533
|
previousValues,
|
|
43413
43534
|
rawObservations: result.observations,
|
|
43414
|
-
recentMessages: formatMessagesForObserver(threadMessages, {
|
|
43535
|
+
recentMessages: () => formatMessagesForObserver(threadMessages, {
|
|
43415
43536
|
maxPartLength: 500,
|
|
43416
43537
|
timeZone: this.opts.record.observedTimezone
|
|
43417
43538
|
}),
|
|
@@ -43640,13 +43761,54 @@ ObservationStrategy.create = ((om, opts) => {
|
|
|
43640
43761
|
if (deps.scope === "resource" && opts.resourceId) return new ResourceScopedObservationStrategy(deps, opts);
|
|
43641
43762
|
return new SyncObservationStrategy(deps, opts);
|
|
43642
43763
|
});
|
|
43764
|
+
/**
|
|
43765
|
+
* Mark the stored history of `threadId` in `messageList` that OM gave new token counts, so the counts are saved
|
|
43766
|
+
* with the messages. Call the returned function once the counting is done: every message holding a part that
|
|
43767
|
+
* gained a count in this process is marked for resave, and the normal save writes it back whole. Counts made
|
|
43768
|
+
* before this is called (while the turn loaded history) are caught too.
|
|
43769
|
+
*
|
|
43770
|
+
* Only messages of `threadId` are marked. A message recalled from another thread of the resource is counted but
|
|
43771
|
+
* never written, because saving it would bump that thread's `updatedAt` and reorder the recent-thread list.
|
|
43772
|
+
*
|
|
43773
|
+
* A Core without `markForResave` is left alone: counting still works, the counts are just not saved.
|
|
43774
|
+
*/
|
|
43775
|
+
function resaveCountedMessagesFor(messageList, threadId) {
|
|
43776
|
+
if (typeof messageList.markForResave !== "function") return () => {};
|
|
43777
|
+
return () => {
|
|
43778
|
+
for (const message of messageList.get.remembered.db()) {
|
|
43779
|
+
if (message.threadId !== threadId) continue;
|
|
43780
|
+
const parts = message.content?.parts ?? [];
|
|
43781
|
+
if (!parts.some(hasUnsavedTokenEstimate)) continue;
|
|
43782
|
+
messageList.markForResave(message);
|
|
43783
|
+
parts.forEach(markTokenEstimateSaved);
|
|
43784
|
+
}
|
|
43785
|
+
};
|
|
43786
|
+
}
|
|
43787
|
+
/** The stored messages marked for resave in `messageList`; none for a Core without `markForResave`. */
|
|
43788
|
+
function messagesMarkedForResave(messageList) {
|
|
43789
|
+
return typeof messageList.getMessagesToResave === "function" ? messageList.getMessagesToResave() : [];
|
|
43790
|
+
}
|
|
43791
|
+
/**
|
|
43792
|
+
* Ids of the stored messages marked for resave in `messageList` that are not in `ownMessages` (the turn's
|
|
43793
|
+
* own input and output). Those are saved whole; the rest only gained counts and are patched onto storage.
|
|
43794
|
+
*/
|
|
43795
|
+
function idsMarkedForResave(messageList, ownMessages = []) {
|
|
43796
|
+
const own = new Set(ownMessages.map((message) => message.id));
|
|
43797
|
+
return new Set(messagesMarkedForResave(messageList).map((message) => message.id).filter((id) => !own.has(id)));
|
|
43798
|
+
}
|
|
43799
|
+
/** `messages` with the messages marked for resave added, each message once. */
|
|
43800
|
+
function withMessagesMarkedForResave(messageList, messages) {
|
|
43801
|
+
const ids = new Set(messages.map((message) => message.id));
|
|
43802
|
+
return [...messages, ...messagesMarkedForResave(messageList).filter((message) => !ids.has(message.id))];
|
|
43803
|
+
}
|
|
43643
43804
|
async function loadMemoryContextMessages({ memory, messageList, threadId, resourceId, runState }) {
|
|
43644
43805
|
const ctx = await memory.getContext({
|
|
43645
43806
|
threadId,
|
|
43646
43807
|
resourceId,
|
|
43647
43808
|
runState
|
|
43648
43809
|
});
|
|
43649
|
-
|
|
43810
|
+
const messages = ctx.messages.filter((msg) => msg.role !== "system");
|
|
43811
|
+
if (messages.length) messageList.add(messages, "memory");
|
|
43650
43812
|
return ctx;
|
|
43651
43813
|
}
|
|
43652
43814
|
function hasPendingToolCall(message) {
|
|
@@ -43740,7 +43902,7 @@ var ObservationStep = class {
|
|
|
43740
43902
|
}
|
|
43741
43903
|
/** Step context from prepare(). Throws if prepare() hasn't been called. */
|
|
43742
43904
|
get context() {
|
|
43743
|
-
if (!this._context) throw new Error("Step not prepared yet
|
|
43905
|
+
if (!this._context) throw new Error("Step not prepared yet \u2014 call prepare() first");
|
|
43744
43906
|
return this._context;
|
|
43745
43907
|
}
|
|
43746
43908
|
/**
|
|
@@ -43851,7 +44013,7 @@ var ObservationStep = class {
|
|
|
43851
44013
|
const inputIds = new Set(messageList.get.input.db().map((msg) => msg.id));
|
|
43852
44014
|
const sealedOutput = safeCandidates.filter((msg) => !inputIds.has(msg.id));
|
|
43853
44015
|
messageList.removeByIds(sealedOutput.map((msg) => msg.id));
|
|
43854
|
-
|
|
44016
|
+
if (sealedOutput.length) messageList.add(sealedOutput, "memory");
|
|
43855
44017
|
}
|
|
43856
44018
|
if (!deferred) {
|
|
43857
44019
|
om.trackBackgroundWork(om.buffer({
|
|
@@ -43900,7 +44062,7 @@ var ObservationStep = class {
|
|
|
43900
44062
|
}).map((msg) => msg.id);
|
|
43901
44063
|
inFlightIds = [...new Set(unreadIds)];
|
|
43902
44064
|
if (messagesToSave.length > 0) {
|
|
43903
|
-
|
|
44065
|
+
messageList.add(messagesToSave, "memory");
|
|
43904
44066
|
try {
|
|
43905
44067
|
await om.persistMessages(messagesToSave, threadId, resourceId);
|
|
43906
44068
|
} catch (error) {
|
|
@@ -44160,7 +44322,7 @@ var ObservationStep = class {
|
|
|
44160
44322
|
const messagesToSeal = messageToSeal ? [messageToSeal] : [];
|
|
44161
44323
|
this.turn.abortSignal?.throwIfAborted();
|
|
44162
44324
|
om.sealMessagesForBuffering(messagesToSeal);
|
|
44163
|
-
if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation
|
|
44325
|
+
if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation \u2014 step-0 seeded response message holds the active id");
|
|
44164
44326
|
else try {
|
|
44165
44327
|
await this.turn.hooks?.onSyncObservationComplete?.();
|
|
44166
44328
|
} catch (error) {
|
|
@@ -44310,12 +44472,12 @@ var ObservationTurn = class {
|
|
|
44310
44472
|
messageList;
|
|
44311
44473
|
/** The current cached record. Refreshed after mutations (activate/observe/reflect). */
|
|
44312
44474
|
get record() {
|
|
44313
|
-
if (!this._record) throw new Error("Turn not started
|
|
44475
|
+
if (!this._record) throw new Error("Turn not started \u2014 call start() first");
|
|
44314
44476
|
return this._record;
|
|
44315
44477
|
}
|
|
44316
44478
|
/** The context loaded during start(). */
|
|
44317
44479
|
get context() {
|
|
44318
|
-
if (!this._context) throw new Error("Turn not started
|
|
44480
|
+
if (!this._context) throw new Error("Turn not started \u2014 call start() first");
|
|
44319
44481
|
return this._context;
|
|
44320
44482
|
}
|
|
44321
44483
|
/** Whether the turn has been ended and can no longer accept steps. */
|
|
@@ -44384,7 +44546,7 @@ var ObservationTurn = class {
|
|
|
44384
44546
|
* (its output messages will be saved at the start of the new step's prepare()).
|
|
44385
44547
|
*/
|
|
44386
44548
|
step(stepNumber) {
|
|
44387
|
-
if (!this._started) throw new Error("Turn not started
|
|
44549
|
+
if (!this._started) throw new Error("Turn not started \u2014 call start() first");
|
|
44388
44550
|
if (this._ended) throw new Error("Turn already ended");
|
|
44389
44551
|
this._currentStep = new ObservationStep(this, stepNumber);
|
|
44390
44552
|
return this._currentStep;
|
|
@@ -44402,8 +44564,8 @@ var ObservationTurn = class {
|
|
|
44402
44564
|
this._ended = true;
|
|
44403
44565
|
const unsavedInput = messageList.get.input.db();
|
|
44404
44566
|
const unsavedOutput = messageList.get.response.db();
|
|
44405
|
-
const unsavedMessages = [...unsavedInput, ...unsavedOutput];
|
|
44406
|
-
if (unsavedMessages.length > 0) await this.om.persistMessages(unsavedMessages, this.threadId, this.resourceId);
|
|
44567
|
+
const unsavedMessages = withMessagesMarkedForResave(messageList, [...unsavedInput, ...unsavedOutput]);
|
|
44568
|
+
if (unsavedMessages.length > 0) await this.om.persistMessages(unsavedMessages, this.threadId, this.resourceId, idsMarkedForResave(messageList, [...unsavedInput, ...unsavedOutput]));
|
|
44407
44569
|
const asyncObservationEnabled = this.om.buffering.isAsyncObservationEnabled();
|
|
44408
44570
|
const bufferOnIdle = this.om.getObservationConfig().bufferOnIdle;
|
|
44409
44571
|
if (!this.abortSignal?.aborted && asyncObservationEnabled && bufferOnIdle) {
|
|
@@ -44605,8 +44767,8 @@ When consolidating observations:
|
|
|
44605
44767
|
- 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
|
|
44606
44768
|
- Prefer many short factual lines over prose summaries. Do not replace facts with generalities like "discussed travel plans"
|
|
44607
44769
|
- Combine related items where it makes sense (e.g., "agent called view tool 5 times on file x")
|
|
44608
|
-
- Preserve
|
|
44609
|
-
- Preserve the concrete resolved outcome captured by
|
|
44770
|
+
- Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
|
|
44771
|
+
- Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
|
|
44610
44772
|
- Condense the wording of older observations more than recent ones, but keep their facts
|
|
44611
44773
|
|
|
44612
44774
|
CRITICAL: USER ASSERTIONS vs QUESTIONS
|
|
@@ -44628,23 +44790,23 @@ When observations contain <thread id="..."> sections:
|
|
|
44628
44790
|
Example input:
|
|
44629
44791
|
<thread id="thread-1">
|
|
44630
44792
|
Date: Dec 4, 2025
|
|
44631
|
-
*
|
|
44632
|
-
*
|
|
44793
|
+
* \u{1F534} (14:30) User prefers TypeScript
|
|
44794
|
+
* \u{1F7E1} (14:35) Working on auth feature
|
|
44633
44795
|
</thread>
|
|
44634
44796
|
<thread id="thread-2">
|
|
44635
44797
|
Date: Dec 4, 2025
|
|
44636
|
-
*
|
|
44637
|
-
*
|
|
44798
|
+
* \u{1F534} (15:00) User prefers TypeScript
|
|
44799
|
+
* \u{1F7E1} (15:05) Debugging API endpoint
|
|
44638
44800
|
</thread>
|
|
44639
44801
|
|
|
44640
44802
|
Example output (consolidated):
|
|
44641
44803
|
Date: Dec 4, 2025
|
|
44642
|
-
*
|
|
44804
|
+
* \u{1F534} (14:30) User prefers TypeScript
|
|
44643
44805
|
<thread id="thread-1">
|
|
44644
|
-
*
|
|
44806
|
+
* \u{1F7E1} (14:35) Working on auth feature
|
|
44645
44807
|
</thread>
|
|
44646
44808
|
<thread id="thread-2">
|
|
44647
|
-
*
|
|
44809
|
+
* \u{1F7E1} (15:05) Debugging API endpoint
|
|
44648
44810
|
</thread>
|
|
44649
44811
|
|
|
44650
44812
|
=== OUTPUT FORMAT ===
|
|
@@ -44675,8 +44837,8 @@ Please re-process with slightly more compression:
|
|
|
44675
44837
|
- Memory is getting long - use a more condensed style throughout
|
|
44676
44838
|
- Combine related items more aggressively but do not lose important specific details of names, places, events, and people
|
|
44677
44839
|
- 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
|
|
44678
|
-
- Preserve
|
|
44679
|
-
- Preserve the concrete resolved outcome captured by
|
|
44840
|
+
- Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
|
|
44841
|
+
- Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
|
|
44680
44842
|
|
|
44681
44843
|
Aim for a 8/10 detail level.
|
|
44682
44844
|
`,
|
|
@@ -44692,8 +44854,8 @@ Please re-process with much more aggressive compression:
|
|
|
44692
44854
|
- Combine related items aggressively but do not lose important specific details of names, places, events, and people
|
|
44693
44855
|
- 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
|
|
44694
44856
|
- If the same file or module is mentioned across many observations, merge into one entry covering the full arc
|
|
44695
|
-
- Preserve
|
|
44696
|
-
- Preserve the concrete resolved outcome captured by
|
|
44857
|
+
- Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
|
|
44858
|
+
- Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
|
|
44697
44859
|
- Remove redundant information and merge overlapping observations
|
|
44698
44860
|
|
|
44699
44861
|
Aim for a 6/10 detail level.
|
|
@@ -44704,14 +44866,14 @@ Aim for a 6/10 detail level.
|
|
|
44704
44866
|
Your previous reflections have failed to compress sufficiently after multiple attempts.
|
|
44705
44867
|
|
|
44706
44868
|
Please re-process with maximum compression:
|
|
44707
|
-
- Summarize the oldest observations (first 50-70%) into brief high-level paragraphs
|
|
44869
|
+
- Summarize the oldest observations (first 50-70%) into brief high-level paragraphs \u2014 only key facts, decisions, and outcomes
|
|
44708
44870
|
- For the most recent observations (last 30-50%), retain important details but still use a condensed style
|
|
44709
|
-
- Ruthlessly merge related observations
|
|
44710
|
-
- Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries
|
|
44711
|
-
- Drop procedural details (tool calls, retries, intermediate steps)
|
|
44871
|
+
- Ruthlessly merge related observations \u2014 if 10 observations are about the same topic, combine into 1-2 lines
|
|
44872
|
+
- Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries \u2014 drop individual steps entirely
|
|
44873
|
+
- Drop procedural details (tool calls, retries, intermediate steps) \u2014 keep only final outcomes
|
|
44712
44874
|
- Drop observations that are no longer relevant or have been superseded by newer information
|
|
44713
|
-
- Preserve
|
|
44714
|
-
- Preserve the concrete resolved outcome captured by
|
|
44875
|
+
- Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
|
|
44876
|
+
- Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
|
|
44715
44877
|
- Preserve: names, dates, decisions, errors, user preferences, and architectural choices
|
|
44716
44878
|
|
|
44717
44879
|
Aim for a 4/10 detail level.
|
|
@@ -44722,14 +44884,14 @@ Aim for a 4/10 detail level.
|
|
|
44722
44884
|
Multiple compression attempts have failed. The content may already be dense from a prior reflection.
|
|
44723
44885
|
|
|
44724
44886
|
You MUST dramatically reduce the number of observations while keeping the standard observation format (date groups with bullet points and priority emojis):
|
|
44725
|
-
- Tool call observations are the biggest source of bloat. Collapse ALL tool call sequences into outcome-only observations
|
|
44726
|
-
- Never preserve individual tool calls (viewed file X, searched for Y, ran build)
|
|
44887
|
+
- 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")
|
|
44888
|
+
- Never preserve individual tool calls (viewed file X, searched for Y, ran build) \u2014 only preserve what was discovered or accomplished
|
|
44727
44889
|
- Consolidate many related observations into single, more generic observations
|
|
44728
44890
|
- Merge all same-day date groups into at most 2-3 date groups per day
|
|
44729
44891
|
- For older content, each topic or task should be at most 1-2 observations capturing the key outcome
|
|
44730
44892
|
- For recent content, retain more detail but still merge related items aggressively
|
|
44731
44893
|
- If multiple observations describe incremental progress on the same task, keep only the final state
|
|
44732
|
-
- Preserve
|
|
44894
|
+
- Preserve \u2705 completion markers and their outcomes but merge related completions into fewer lines
|
|
44733
44895
|
- Preserve: user preferences, key decisions, architectural choices, and unresolved issues
|
|
44734
44896
|
|
|
44735
44897
|
Aim for a 2/10 detail level. Fewer, more generic observations are better than many specific ones that exceed the budget.
|
|
@@ -45152,7 +45314,7 @@ var ReflectorRunner = class {
|
|
|
45152
45314
|
operationType: "reflection",
|
|
45153
45315
|
startedAt: streamContext.startedAt,
|
|
45154
45316
|
tokensAttempted: originalTokens,
|
|
45155
|
-
error: `Did not compress below threshold (${originalTokens}
|
|
45317
|
+
error: `Did not compress below threshold (${originalTokens} \u2192 ${reflectedTokens}, target: ${targetThreshold}), retrying at level ${currentLevel + 1}`,
|
|
45156
45318
|
retrying: true,
|
|
45157
45319
|
recordId: streamContext.recordId,
|
|
45158
45320
|
threadId: streamContext.threadId
|
|
@@ -45182,7 +45344,7 @@ var ReflectorRunner = class {
|
|
|
45182
45344
|
}
|
|
45183
45345
|
currentLevel = Math.min(currentLevel + 1, maxLevel);
|
|
45184
45346
|
}
|
|
45185
|
-
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)" : ""}
|
|
45347
|
+
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`);
|
|
45186
45348
|
const structuredExtraction = await extractStructuredValues({
|
|
45187
45349
|
agent,
|
|
45188
45350
|
source: "reflector",
|
|
@@ -45323,7 +45485,7 @@ var ReflectorRunner = class {
|
|
|
45323
45485
|
const reflectedObservationLineCount = linesToReflect;
|
|
45324
45486
|
const sliceTokenEstimate = Math.round(avgTokensPerLine * linesToReflect);
|
|
45325
45487
|
const compressionTarget = Math.round(sliceTokenEstimate * .75);
|
|
45326
|
-
omDebug(`[OM:reflect] doAsyncBufferedReflection: slicing observations for reflection
|
|
45488
|
+
omDebug(`[OM:reflect] doAsyncBufferedReflection: slicing observations for reflection \u2014 totalLines=${totalLines}, avgTokPerLine=${avgTokensPerLine.toFixed(1)}, activationPointTokens=${activationPointTokens}, linesToReflect=${linesToReflect}/${totalLines}, sliceTokenEstimate=${sliceTokenEstimate}, compressionTarget=${compressionTarget}`);
|
|
45327
45489
|
omDebug(`[OM:reflect] doAsyncBufferedReflection: starting reflector call, recordId=${currentRecord.id}, observationTokens=${sliceTokenEstimate}, compressionTarget=${compressionTarget} (inputTokens), activeObsLength=${activeObservations.length}, reflectedLineCount=${reflectedObservationLineCount}`);
|
|
45328
45490
|
if (writer) {
|
|
45329
45491
|
const startMarker = createBufferingStartMarker({
|
|
@@ -45495,7 +45657,7 @@ var ReflectorRunner = class {
|
|
|
45495
45657
|
const unreflectedTailTokens = unreflectedContent ? this.tokenCounter.countObservations(unreflectedContent) : 0;
|
|
45496
45658
|
const bufferedReflectionTokens = freshRecord.bufferedReflectionTokens ?? 0;
|
|
45497
45659
|
if (unreflectedTailTokens < bufferedReflectionTokens) {
|
|
45498
|
-
omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation
|
|
45660
|
+
omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation \u2014 unreflectedTailTokens=${unreflectedTailTokens} < bufferedReflectionTokens=${bufferedReflectionTokens}; keeping buffer for threshold activation`);
|
|
45499
45661
|
return {
|
|
45500
45662
|
status: "suppressed",
|
|
45501
45663
|
reason: "composition"
|
|
@@ -45506,7 +45668,7 @@ var ReflectorRunner = class {
|
|
|
45506
45668
|
const regularActivationTarget = reflectThreshold * (1 - bufferActivation);
|
|
45507
45669
|
const minCombinedTokens = Math.round(regularActivationTarget * EARLY_ACTIVATION_SIZE_FLOOR_RATIO);
|
|
45508
45670
|
if (combinedTokenCount < minCombinedTokens) {
|
|
45509
|
-
omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation
|
|
45671
|
+
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`);
|
|
45510
45672
|
return {
|
|
45511
45673
|
status: "suppressed",
|
|
45512
45674
|
reason: "size"
|
|
@@ -45635,7 +45797,7 @@ var ReflectorRunner = class {
|
|
|
45635
45797
|
omDebug(`[OM:reflect] isReflecting=true and active in this process, skipping`);
|
|
45636
45798
|
return;
|
|
45637
45799
|
}
|
|
45638
|
-
omDebug(`[OM:reflect] isReflecting=true but NOT active in this process
|
|
45800
|
+
omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
|
|
45639
45801
|
await this.storage.setReflectingFlag(record.id, false);
|
|
45640
45802
|
}
|
|
45641
45803
|
if (this.buffering.isAsyncReflectionEnabled()) {
|
|
@@ -45649,15 +45811,15 @@ var ReflectorRunner = class {
|
|
|
45649
45811
|
else {
|
|
45650
45812
|
const activationPoint = reflectThreshold * this.reflectionConfig.bufferActivation;
|
|
45651
45813
|
if (observationTokens < activationPoint) {
|
|
45652
|
-
omDebug(`[OM:reflect] skipping async reflection
|
|
45814
|
+
omDebug(`[OM:reflect] skipping async reflection \u2014 observationTokens (${observationTokens}) below activation point (${activationPoint}), triggered by ${activationTriggeredBy}`);
|
|
45653
45815
|
return;
|
|
45654
45816
|
}
|
|
45655
45817
|
const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
|
|
45656
45818
|
if (this.buffering.isAsyncBufferingInProgress(bufferKey) || BufferingCoordinator.lastBufferedBoundary.has(bufferKey)) {
|
|
45657
|
-
omDebug(`[OM:reflect] skipping async reflection
|
|
45819
|
+
omDebug(`[OM:reflect] skipping async reflection \u2014 reflection buffer already active or present for ${bufferKey}`);
|
|
45658
45820
|
return;
|
|
45659
45821
|
}
|
|
45660
|
-
omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter})
|
|
45822
|
+
omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) \u2014 starting background reflection`);
|
|
45661
45823
|
this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
|
|
45662
45824
|
return;
|
|
45663
45825
|
}
|
|
@@ -45665,7 +45827,7 @@ var ReflectorRunner = class {
|
|
|
45665
45827
|
if (activationTriggeredBy === "threshold") {
|
|
45666
45828
|
const suppressedAtTokens = this.syncReflectionSuppression.get(lockKey);
|
|
45667
45829
|
if (suppressedAtTokens !== void 0 && observationTokens === suppressedAtTokens) {
|
|
45668
|
-
omDebug(`[OM:reflect] skipping sync reflection
|
|
45830
|
+
omDebug(`[OM:reflect] skipping sync reflection \u2014 observations unchanged at ${observationTokens} tokens since the last unproductive attempt; retrying once they change`);
|
|
45669
45831
|
return;
|
|
45670
45832
|
}
|
|
45671
45833
|
}
|
|
@@ -46506,7 +46668,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
46506
46668
|
const asyncBufferingDisabled = config.observation?.bufferTokens === false || config.scope === "resource" && !userExplicitlyConfiguredAsync;
|
|
46507
46669
|
if (isSharedBudget && !asyncBufferingDisabled) {
|
|
46508
46670
|
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).");
|
|
46509
|
-
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
|
|
46671
|
+
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.");
|
|
46510
46672
|
}
|
|
46511
46673
|
const observationActivateAfterIdle = config.observation?.activateAfterIdle ?? config.activateAfterIdle;
|
|
46512
46674
|
const observationActivateAfterIdlePath = config.observation?.activateAfterIdle !== void 0 ? "observation.activateAfterIdle" : "activateAfterIdle";
|
|
@@ -46603,7 +46765,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
46603
46765
|
hasWarnedResourceScopeDeprecation = true;
|
|
46604
46766
|
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");
|
|
46605
46767
|
}
|
|
46606
|
-
omDebug(`[OM:init] new ObservationalMemory instance created
|
|
46768
|
+
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}`);
|
|
46607
46769
|
}
|
|
46608
46770
|
__registerMastra(mastra) {
|
|
46609
46771
|
this.mastra = mastra;
|
|
@@ -46884,7 +47046,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
46884
47046
|
threadId: null,
|
|
46885
47047
|
resourceId: resourceId ?? threadId
|
|
46886
47048
|
};
|
|
46887
|
-
if (!threadId) throw new Error("ObservationalMemory (scope: 'thread') requires a threadId, but received an empty value. This is a bug
|
|
47049
|
+
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.");
|
|
46888
47050
|
return {
|
|
46889
47051
|
threadId,
|
|
46890
47052
|
resourceId: resourceId ?? threadId
|
|
@@ -47195,7 +47357,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
47195
47357
|
const isImportant = new Array(totalCount);
|
|
47196
47358
|
for (let i = 0; i < totalCount; i++) {
|
|
47197
47359
|
lineTokens[i] = this.tokenCounter.countString(lines[i]);
|
|
47198
|
-
isImportant[i] = lines[i].includes("
|
|
47360
|
+
isImportant[i] = lines[i].includes("\u{1F534}") || lines[i].includes("\u2705");
|
|
47199
47361
|
}
|
|
47200
47362
|
const suffixTokens = new Array(totalCount + 1);
|
|
47201
47363
|
suffixTokens[totalCount] = 0;
|
|
@@ -47307,18 +47469,86 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
47307
47469
|
* to detect already-persisted messages, avoiding redundant DB operations.
|
|
47308
47470
|
*
|
|
47309
47471
|
* Messages with observation markers are always saved (upserted) even if sealed,
|
|
47310
|
-
* because the markers need to be persisted to storage.
|
|
47472
|
+
* because the markers need to be persisted to storage. A stored message in `resaveIds` gained token
|
|
47473
|
+
* counts after it was stored, whether or not it is sealed: only those counts are copied onto the stored
|
|
47474
|
+
* 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
|
|
47475
|
+
* input or output, which are saved whole.
|
|
47311
47476
|
*/
|
|
47312
|
-
async persistMessages(messagesToSave, threadId, resourceId) {
|
|
47477
|
+
async persistMessages(messagesToSave, threadId, resourceId, resaveIds) {
|
|
47313
47478
|
const filteredMessages = [];
|
|
47314
|
-
|
|
47315
|
-
|
|
47316
|
-
|
|
47479
|
+
const storedWithNewCounts = [];
|
|
47480
|
+
for (const msg of messagesToSave) {
|
|
47481
|
+
if (!!(msg.content?.metadata)?.mastra?.sealed && findLastCompletedObservationBoundary(msg) === -1 && !resaveIds?.has(msg.id)) continue;
|
|
47482
|
+
if (resaveIds?.has(msg.id) && findLastCompletedObservationBoundary(msg) === -1) storedWithNewCounts.push(msg);
|
|
47483
|
+
else filteredMessages.push(msg);
|
|
47484
|
+
}
|
|
47317
47485
|
if (filteredMessages.length > 0) await this.messageHistory.persistMessages({
|
|
47318
47486
|
messages: filteredMessages,
|
|
47319
47487
|
threadId,
|
|
47320
47488
|
resourceId
|
|
47321
47489
|
});
|
|
47490
|
+
try {
|
|
47491
|
+
await this.persistTokenEstimatesOntoStored(storedWithNewCounts);
|
|
47492
|
+
} catch (error) {
|
|
47493
|
+
omError("[OM] Failed to save token counts for stored messages", error);
|
|
47494
|
+
}
|
|
47495
|
+
}
|
|
47496
|
+
/**
|
|
47497
|
+
* Copy the token counts of `messages` onto their stored copies. A stored copy can hold
|
|
47498
|
+
* parts the in-memory one lacks (markers written straight to storage), so it is patched
|
|
47499
|
+
* instead of saved whole. Each count goes to the first stored part whose content matches the counted
|
|
47500
|
+
* part, so a part that changed in storage keeps no count and is counted again on read.
|
|
47501
|
+
*/
|
|
47502
|
+
async persistTokenEstimatesOntoStored(messages) {
|
|
47503
|
+
if (messages.length === 0) return;
|
|
47504
|
+
const contentOf = (part) => {
|
|
47505
|
+
const { tokenEstimate: _tokenEstimate, ...mastra } = part.providerMetadata?.mastra ?? {};
|
|
47506
|
+
return JSON.stringify({
|
|
47507
|
+
...part,
|
|
47508
|
+
providerMetadata: {
|
|
47509
|
+
...part.providerMetadata,
|
|
47510
|
+
mastra
|
|
47511
|
+
}
|
|
47512
|
+
});
|
|
47513
|
+
};
|
|
47514
|
+
const live = new Map(messages.map((message) => [message.id, message]));
|
|
47515
|
+
const { messages: stored } = await this.storage.listMessagesById({ messageIds: [...live.keys()] });
|
|
47516
|
+
const updates = [];
|
|
47517
|
+
for (const row of stored) {
|
|
47518
|
+
const counts = /* @__PURE__ */ new Map();
|
|
47519
|
+
for (const part of live.get(row.id)?.content.parts ?? []) {
|
|
47520
|
+
const tokenEstimate = part.providerMetadata?.mastra?.tokenEstimate;
|
|
47521
|
+
if (!tokenEstimate) continue;
|
|
47522
|
+
const key = contentOf(part);
|
|
47523
|
+
counts.set(key, [...counts.get(key) ?? [], tokenEstimate]);
|
|
47524
|
+
}
|
|
47525
|
+
if (counts.size === 0) continue;
|
|
47526
|
+
let changed = false;
|
|
47527
|
+
const parts = row.content.parts.map((part) => {
|
|
47528
|
+
const tokenEstimate = counts.get(contentOf(part))?.shift();
|
|
47529
|
+
if (!tokenEstimate) return part;
|
|
47530
|
+
changed = true;
|
|
47531
|
+
const providerMetadata = part.providerMetadata ?? {};
|
|
47532
|
+
return {
|
|
47533
|
+
...part,
|
|
47534
|
+
providerMetadata: {
|
|
47535
|
+
...providerMetadata,
|
|
47536
|
+
mastra: {
|
|
47537
|
+
...providerMetadata.mastra,
|
|
47538
|
+
tokenEstimate
|
|
47539
|
+
}
|
|
47540
|
+
}
|
|
47541
|
+
};
|
|
47542
|
+
});
|
|
47543
|
+
if (changed) updates.push({
|
|
47544
|
+
id: row.id,
|
|
47545
|
+
content: {
|
|
47546
|
+
...row.content,
|
|
47547
|
+
parts
|
|
47548
|
+
}
|
|
47549
|
+
});
|
|
47550
|
+
}
|
|
47551
|
+
if (updates.length > 0) await this.storage.updateMessages({ messages: updates });
|
|
47322
47552
|
}
|
|
47323
47553
|
/**
|
|
47324
47554
|
* Load messages from storage that haven't been observed yet.
|
|
@@ -47528,7 +47758,7 @@ ${formattedMessages}
|
|
|
47528
47758
|
resourceId: freshRecord.resourceId ?? void 0
|
|
47529
47759
|
});
|
|
47530
47760
|
} catch (err) {
|
|
47531
|
-
omError("[OM] Failed to persist sealed messages before buffering
|
|
47761
|
+
omError("[OM] Failed to persist sealed messages before buffering \u2014 skipping observation cycle", err);
|
|
47532
47762
|
return;
|
|
47533
47763
|
}
|
|
47534
47764
|
const cycleId = `buffer-obs-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
|
|
@@ -48678,7 +48908,7 @@ ${formattedMessages}
|
|
|
48678
48908
|
usage: void 0
|
|
48679
48909
|
};
|
|
48680
48910
|
}
|
|
48681
|
-
omDebug(`[OM:reflect] isReflecting=true but NOT active in this process
|
|
48911
|
+
omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
|
|
48682
48912
|
await this.storage.setReflectingFlag(record.id, false);
|
|
48683
48913
|
}
|
|
48684
48914
|
await this.storage.setReflectingFlag(record.id, true);
|
|
@@ -48912,7 +49142,7 @@ ${formattedMessages}
|
|
|
48912
49142
|
};
|
|
48913
49143
|
const TEMPORAL_GAP_REMINDER_TYPE = "temporal-gap";
|
|
48914
49144
|
function getTemporalGapReminderText(gapText, timestamp) {
|
|
48915
|
-
return `${gapText}
|
|
49145
|
+
return `${gapText} \u2014 ${formatTemporalTimestamp(new Date(timestamp))}`;
|
|
48916
49146
|
}
|
|
48917
49147
|
function getTemporalGapReminderMetadata(message, gapText, gapMs, timestamp) {
|
|
48918
49148
|
const formattedTimestamp = formatTemporalTimestamp(new Date(timestamp));
|
|
@@ -49119,11 +49349,12 @@ var ObservationalMemoryProcessor = class {
|
|
|
49119
49349
|
state.__omTurn = void 0;
|
|
49120
49350
|
if (!activeTurn || activeTurn.ended) return;
|
|
49121
49351
|
const terminalList = messageList ?? activeTurn.messageList;
|
|
49122
|
-
const
|
|
49352
|
+
const ownMessages = [...terminalList.get.input.db(), ...terminalList.get.response.db()];
|
|
49353
|
+
const unsavedMessages = withMessagesMarkedForResave(terminalList, ownMessages);
|
|
49123
49354
|
try {
|
|
49124
49355
|
await activeTurn.end(terminalList);
|
|
49125
49356
|
} catch (error) {
|
|
49126
|
-
if (unsavedMessages.length > 0) await this.engine.persistMessages(unsavedMessages, activeTurn.threadId, activeTurn.resourceId).catch(() => {});
|
|
49357
|
+
if (unsavedMessages.length > 0) await this.engine.persistMessages(unsavedMessages, activeTurn.threadId, activeTurn.resourceId, idsMarkedForResave(terminalList, ownMessages)).catch(() => {});
|
|
49127
49358
|
throw error;
|
|
49128
49359
|
}
|
|
49129
49360
|
}
|
|
@@ -49133,14 +49364,14 @@ var ObservationalMemoryProcessor = class {
|
|
|
49133
49364
|
omDebug(`[OM:processInputStep:ENTER] step=${stepNumber}, hasMastraMemory=${!!requestContext?.get("MastraMemory")}, hasMemoryInfo=${!!messageList?.serialize()?.memoryInfo?.threadId}`);
|
|
49134
49365
|
const context = this.engine.getThreadContext(requestContext, messageList);
|
|
49135
49366
|
if (!context) {
|
|
49136
|
-
omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null
|
|
49367
|
+
omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null \u2014 returning early`);
|
|
49137
49368
|
return messageList;
|
|
49138
49369
|
}
|
|
49139
49370
|
const gatewayMemoryManaged = await isGatewayMemoryManaged(model);
|
|
49140
49371
|
state[GATEWAY_STATE_KEY] = gatewayMemoryManaged;
|
|
49141
49372
|
if (gatewayMemoryManaged) {
|
|
49142
49373
|
await this.endActiveTurn(state);
|
|
49143
|
-
omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory
|
|
49374
|
+
omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory \u2014 skipping local processing`);
|
|
49144
49375
|
return messageList;
|
|
49145
49376
|
}
|
|
49146
49377
|
const { threadId, resourceId } = context;
|
|
@@ -49265,6 +49496,7 @@ var ObservationalMemoryProcessor = class {
|
|
|
49265
49496
|
this.turn.responseMessageId = responseMessageId;
|
|
49266
49497
|
{
|
|
49267
49498
|
const step = this.turn.step(stepNumber);
|
|
49499
|
+
const resaveCounted = resaveCountedMessagesFor(messageList, threadId);
|
|
49268
49500
|
let ctx;
|
|
49269
49501
|
try {
|
|
49270
49502
|
ctx = await step.prepare();
|
|
@@ -49299,6 +49531,7 @@ var ObservationalMemoryProcessor = class {
|
|
|
49299
49531
|
threadId,
|
|
49300
49532
|
resourceId
|
|
49301
49533
|
});
|
|
49534
|
+
resaveCounted();
|
|
49302
49535
|
const finalTotalPending = ctx.status.pendingTokens;
|
|
49303
49536
|
try {
|
|
49304
49537
|
await runOMCommit(this.engine.buffering.getLockKey(threadId, resourceId), () => this.engine.getStorage().setPendingMessageTokens(turnRecord.id, finalTotalPending), { abortSignal });
|
|
@@ -49338,6 +49571,7 @@ var ObservationalMemoryProcessor = class {
|
|
|
49338
49571
|
return this.engine.getTokenCounter().runWithModelContext(state.__omActorModelContext, async () => {
|
|
49339
49572
|
if ((0, _mastra_core_memory.parseMemoryRequestContext)(requestContext)?.memoryConfig?.readOnly) return messageList;
|
|
49340
49573
|
const persistenceMessageList = messageList.cloneForPersistence();
|
|
49574
|
+
this.engine.getTokenCounter().countMessages(persistenceMessageList.get.response.db());
|
|
49341
49575
|
const turn = asLiveTurn(state.__omTurn) ?? this.turn;
|
|
49342
49576
|
const liveTurn = turn && !turn.ended ? turn : void 0;
|
|
49343
49577
|
if (liveTurn) await liveTurn.end(persistenceMessageList);
|
|
@@ -49345,8 +49579,9 @@ var ObservationalMemoryProcessor = class {
|
|
|
49345
49579
|
state.__omTurn = void 0;
|
|
49346
49580
|
if (!liveTurn) {
|
|
49347
49581
|
const newOutput = persistenceMessageList.get.response.db();
|
|
49348
|
-
const
|
|
49349
|
-
|
|
49582
|
+
const ownMessages = [...persistenceMessageList.get.input.db(), ...newOutput];
|
|
49583
|
+
const messagesToSave = withMessagesMarkedForResave(persistenceMessageList, ownMessages);
|
|
49584
|
+
if (messagesToSave.length > 0 && context.threadId) await this.engine.persistMessages(messagesToSave, context.threadId, context.resourceId, idsMarkedForResave(persistenceMessageList, ownMessages));
|
|
49350
49585
|
}
|
|
49351
49586
|
return messageList;
|
|
49352
49587
|
});
|
|
@@ -49361,7 +49596,7 @@ var ObservationalMemoryProcessor = class {
|
|
|
49361
49596
|
if (!context) return;
|
|
49362
49597
|
if ((0, _mastra_core_memory.parseMemoryRequestContext)(requestContext)?.memoryConfig?.readOnly) return;
|
|
49363
49598
|
state[CONTEXT_OVERFLOW_STEP_KEY] = stepNumber;
|
|
49364
|
-
omDebug(`[OM:processAPIError] context overflow at step ${stepNumber}
|
|
49599
|
+
omDebug(`[OM:processAPIError] context overflow at step ${stepNumber} \u2014 observing pending messages`);
|
|
49365
49600
|
const { threadId, resourceId } = context;
|
|
49366
49601
|
await this.engine.waitForBuffering(threadId, resourceId, void 0, args.abortSignal);
|
|
49367
49602
|
const messages = getObservableMessages(messageList);
|
|
@@ -51960,7 +52195,7 @@ var require_ignore = /* @__PURE__ */ require_rolldown_runtime.__commonJSMin(((ex
|
|
|
51960
52195
|
const SPACE = " ";
|
|
51961
52196
|
const ESCAPE = "\\";
|
|
51962
52197
|
const REGEX_LITERAL_SPECIAL = /[.*+?()[\]{}^$|\\/]/;
|
|
51963
|
-
const BOM = "
|
|
52198
|
+
const BOM = "\uFEFF";
|
|
51964
52199
|
const REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
|
|
51965
52200
|
const REGEX_ANCHORED_GLOBSTAR = /^\/\*{2,}$/;
|
|
51966
52201
|
const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
|
|
@@ -52057,8 +52292,8 @@ var require_ignore = /* @__PURE__ */ require_rolldown_runtime.__commonJSMin(((ex
|
|
|
52057
52292
|
const NEVER_MATCH = "[]";
|
|
52058
52293
|
const PLACEHOLDER = "\0";
|
|
52059
52294
|
const REGEX_RESTORE_PLACEHOLDER = new RegExp(`${PLACEHOLDER}(\\d+)${PLACEHOLDER}`, "g");
|
|
52060
|
-
const TRAILING_WILDCARD = "
|
|
52061
|
-
const TRAILING_DOUBLESTAR = "
|
|
52295
|
+
const TRAILING_WILDCARD = "\uE000";
|
|
52296
|
+
const TRAILING_DOUBLESTAR = "\uE001";
|
|
52062
52297
|
const isReserved = (char) => char === PLACEHOLDER || char === TRAILING_WILDCARD || char === TRAILING_DOUBLESTAR;
|
|
52063
52298
|
const extractBrackets = (pattern) => {
|
|
52064
52299
|
const sources = [];
|
|
@@ -52830,7 +53065,7 @@ async function logGitState(targetPath, label) {
|
|
|
52830
53065
|
const gitStatusResult = await git(targetPath, "status", "--porcelain");
|
|
52831
53066
|
const gitLogResult = await git(targetPath, "log", "--oneline", "-3");
|
|
52832
53067
|
const gitCountResult = await git(targetPath, "rev-list", "--count", "HEAD");
|
|
52833
|
-
console.info(
|
|
53068
|
+
console.info(`\u{1F4CA} Git state ${label}:`);
|
|
52834
53069
|
console.info("Status:", gitStatusResult.stdout.trim() || "Clean working directory");
|
|
52835
53070
|
console.info("Recent commits:", gitLogResult.stdout.trim());
|
|
52836
53071
|
console.info("Total commits:", gitCountResult.stdout.trim());
|
|
@@ -52922,9 +53157,9 @@ async function gitCheckoutBranch(branchName, targetPath) {
|
|
|
52922
53157
|
async function backupAndReplaceFile(sourceFile, targetFile) {
|
|
52923
53158
|
const backupFile = `${targetFile}.backup-${Date.now()}`;
|
|
52924
53159
|
await (0, fs_promises.copyFile)(targetFile, backupFile);
|
|
52925
|
-
console.info(
|
|
53160
|
+
console.info(`\u{1F4E6} Created backup: ${(0, path.basename)(backupFile)}`);
|
|
52926
53161
|
await (0, fs_promises.copyFile)(sourceFile, targetFile);
|
|
52927
|
-
console.info(
|
|
53162
|
+
console.info(`\u{1F504} Replaced file with template version (backup created)`);
|
|
52928
53163
|
}
|
|
52929
53164
|
async function renameAndCopyFile(sourceFile, targetFile) {
|
|
52930
53165
|
let counter = 1;
|
|
@@ -52938,7 +53173,7 @@ async function renameAndCopyFile(sourceFile, targetFile) {
|
|
|
52938
53173
|
counter++;
|
|
52939
53174
|
}
|
|
52940
53175
|
await (0, fs_promises.copyFile)(sourceFile, uniqueTargetFile);
|
|
52941
|
-
console.info(
|
|
53176
|
+
console.info(`\u{1F4DD} Copied with unique name: ${(0, path.basename)(uniqueTargetFile)}`);
|
|
52942
53177
|
return uniqueTargetFile;
|
|
52943
53178
|
}
|
|
52944
53179
|
const isValidMastraLanguageModel = (model) => {
|
|
@@ -52976,7 +53211,7 @@ const mergeGitignoreFiles = (targetContent, templateContent, templateSlug) => {
|
|
|
52976
53211
|
const isNegation = normalized.startsWith("!");
|
|
52977
53212
|
const basePath = isNegation ? normalized.slice(1) : normalized;
|
|
52978
53213
|
if (!(isNegation ? existingEntries.has(basePath) : existingEntries.has("!" + basePath))) newEntries.push(trimmed);
|
|
52979
|
-
else console.info(
|
|
53214
|
+
else console.info(`\u26A0 Skipping conflicting .gitignore rule: ${trimmed} (conflicts with existing rule)`);
|
|
52980
53215
|
}
|
|
52981
53216
|
}
|
|
52982
53217
|
}
|
|
@@ -53006,7 +53241,7 @@ const mergeEnvFiles = (targetContent, templateVariables, templateSlug) => {
|
|
|
53006
53241
|
key,
|
|
53007
53242
|
value
|
|
53008
53243
|
});
|
|
53009
|
-
else console.info(
|
|
53244
|
+
else console.info(`\u26A0 Skipping existing environment variable: ${key} (already exists in .env)`);
|
|
53010
53245
|
if (newVars.length === 0) return targetContent;
|
|
53011
53246
|
const result = [...targetLines];
|
|
53012
53247
|
const lastLine = result[result.length - 1];
|
|
@@ -53061,7 +53296,7 @@ const createModelInstance = async (provider, modelId, version = "v2") => {
|
|
|
53061
53296
|
try {
|
|
53062
53297
|
const providerFn = version === `v1` ? { v1: {
|
|
53063
53298
|
openai: async () => {
|
|
53064
|
-
const { openai } = await Promise.resolve().then(() => require("./dist-
|
|
53299
|
+
const { openai } = await Promise.resolve().then(() => require("./dist-C5_WGwU1.cjs"));
|
|
53065
53300
|
return openai(modelId);
|
|
53066
53301
|
},
|
|
53067
53302
|
anthropic: async () => {
|
|
@@ -53130,25 +53365,25 @@ IF NO PROJECT EXISTS, USE THE MANAGEPROJECT TOOL TO CREATE A NEW PROJECT
|
|
|
53130
53365
|
|
|
53131
53366
|
DO NOT INCLUDE TODOS IN THE CODE, UNLESS SPECIFICALLY ASKED TO DO SO, CREATE REAL WORLD CODE
|
|
53132
53367
|
|
|
53133
|
-
### 1.
|
|
53368
|
+
### 1. \u{1F50D} **UNDERSTAND** (Information Gathering)
|
|
53134
53369
|
- **Explore Mastra Docs**: Use docs tools to understand relevant Mastra patterns and APIs
|
|
53135
53370
|
- **Analyze Project**: Use file exploration to understand existing codebase structure
|
|
53136
53371
|
- **Web Research**: Search for packages, examples, or solutions when docs are insufficient
|
|
53137
53372
|
- **Clarify Requirements**: Ask targeted questions only when critical information is missing
|
|
53138
53373
|
|
|
53139
|
-
### 2.
|
|
53374
|
+
### 2. \u{1F4CB} **PLAN** (Strategy & Design)
|
|
53140
53375
|
- **Architecture**: Design using Mastra conventions (agents, tools, workflows, memory)
|
|
53141
53376
|
- **Dependencies**: Identify required packages and Mastra components
|
|
53142
53377
|
- **Integration**: Plan how to integrate with existing project structure
|
|
53143
53378
|
- **Validation**: Define how to test and verify the implementation
|
|
53144
53379
|
|
|
53145
|
-
### 3.
|
|
53380
|
+
### 3. \u{1F6E0}\uFE0F **BUILD** (Implementation)
|
|
53146
53381
|
- **Install First**: Use \`manageProject\` tool to install required packages
|
|
53147
53382
|
- **Follow Patterns**: Implement using established Mastra conventions
|
|
53148
53383
|
- **Real Code Only**: Build actual working functionality, never mock implementations
|
|
53149
53384
|
- **Environment Setup**: Create proper .env configuration and documentation
|
|
53150
53385
|
|
|
53151
|
-
### 4.
|
|
53386
|
+
### 4. \u2705 **VALIDATE** (Quality Assurance)
|
|
53152
53387
|
- **Code Validation**: Run \`validateCode\` with types and lint checks
|
|
53153
53388
|
- **Testing**: Execute tests if available
|
|
53154
53389
|
- **Server Testing**: Use \`manageServer\` and \`httpRequest\` for API validation
|
|
@@ -53245,23 +53480,23 @@ DO NOT INCLUDE TODOS IN THE CODE, UNLESS SPECIFICALLY ASKED TO DO SO, CREATE REA
|
|
|
53245
53480
|
## Output Requirements
|
|
53246
53481
|
|
|
53247
53482
|
### Code Quality
|
|
53248
|
-
-
|
|
53249
|
-
-
|
|
53250
|
-
-
|
|
53251
|
-
-
|
|
53252
|
-
-
|
|
53483
|
+
- \u2705 TypeScript compilation passes
|
|
53484
|
+
- \u2705 ESLint validation passes
|
|
53485
|
+
- \u2705 Proper error handling implemented
|
|
53486
|
+
- \u2705 Environment variables configured
|
|
53487
|
+
- \u2705 Tests included when appropriate
|
|
53253
53488
|
|
|
53254
53489
|
### Documentation
|
|
53255
|
-
-
|
|
53256
|
-
-
|
|
53257
|
-
-
|
|
53258
|
-
-
|
|
53490
|
+
- \u2705 Clear setup instructions
|
|
53491
|
+
- \u2705 Environment variable documentation
|
|
53492
|
+
- \u2705 Usage examples provided
|
|
53493
|
+
- \u2705 API documentation for custom tools
|
|
53259
53494
|
|
|
53260
53495
|
### Integration
|
|
53261
|
-
-
|
|
53262
|
-
-
|
|
53263
|
-
-
|
|
53264
|
-
-
|
|
53496
|
+
- \u2705 Follows Mastra conventions
|
|
53497
|
+
- \u2705 Integrates with existing project
|
|
53498
|
+
- \u2705 Proper imports and exports
|
|
53499
|
+
- \u2705 Compatible with Mastra ecosystem
|
|
53265
53500
|
|
|
53266
53501
|
## Project Context
|
|
53267
53502
|
|
|
@@ -53808,7 +54043,7 @@ export const mastra = new Mastra({
|
|
|
53808
54043
|
}),
|
|
53809
54044
|
validateCode: (0, _mastra_core_tools.createTool)({
|
|
53810
54045
|
id: "validate-code",
|
|
53811
|
-
description: "Validates code using a fast hybrid approach: syntax
|
|
54046
|
+
description: "Validates code using a fast hybrid approach: syntax \u2192 semantic \u2192 lint. RECOMMENDED: Always provide specific files for optimal performance and accuracy.",
|
|
53812
54047
|
inputSchema: zod.z.object({
|
|
53813
54048
|
projectPath: zod.z.string().optional().describe("Path to the project to validate (defaults to current project)"),
|
|
53814
54049
|
validationType: zod.z.array(zod.z.enum([
|
|
@@ -53818,7 +54053,7 @@ export const mastra = new Mastra({
|
|
|
53818
54053
|
"tests",
|
|
53819
54054
|
"build"
|
|
53820
54055
|
])).describe("Types of validation to perform. Recommended: [\"types\", \"lint\"] for code quality"),
|
|
53821
|
-
files: zod.z.array(zod.z.string()).optional().describe("RECOMMENDED: Specific files to validate (e.g., files you created/modified). Uses hybrid validation: fast syntax check
|
|
54056
|
+
files: zod.z.array(zod.z.string()).optional().describe("RECOMMENDED: Specific files to validate (e.g., files you created/modified). Uses hybrid validation: fast syntax check \u2192 semantic types \u2192 ESLint. Without files, falls back to slower CLI validation.")
|
|
53822
54057
|
}),
|
|
53823
54058
|
outputSchema: zod.z.object({
|
|
53824
54059
|
valid: zod.z.boolean(),
|
|
@@ -55701,8 +55936,8 @@ For each Mastra project directory you analyze:
|
|
|
55701
55936
|
IMPORTANT - Naming Consistency Rules:
|
|
55702
55937
|
- For ALL unit types (including 'other'), the 'name' field should be the filename WITHOUT extension
|
|
55703
55938
|
- For structured units (agents, workflows, tools, etc.), prefer the actual export name if clearly identifiable
|
|
55704
|
-
- use the base filename without extension for the id (e.g., 'util.ts'
|
|
55705
|
-
- use the relative path from the template root for the file (e.g., 'src/mastra/lib/util.ts'
|
|
55939
|
+
- use the base filename without extension for the id (e.g., 'util.ts' \u2192 name: 'util')
|
|
55940
|
+
- 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')
|
|
55706
55941
|
|
|
55707
55942
|
Return the actual exported names of the units, as well as the file names.`,
|
|
55708
55943
|
name: "Mastra Project Discoverer",
|
|
@@ -56058,7 +56293,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56058
56293
|
sourceFile: unit.file,
|
|
56059
56294
|
targetFile: `${targetDir}/${convertedFileName}`
|
|
56060
56295
|
});
|
|
56061
|
-
console.info(
|
|
56296
|
+
console.info(`\u23ED\uFE0F Skipped ${unit.kind} "${unit.id}": file already exists`);
|
|
56062
56297
|
continue;
|
|
56063
56298
|
case "backup-and-replace": try {
|
|
56064
56299
|
await backupAndReplaceFile(sourceFile, targetFile);
|
|
@@ -56070,7 +56305,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56070
56305
|
id: unit.id
|
|
56071
56306
|
}
|
|
56072
56307
|
});
|
|
56073
|
-
console.info(
|
|
56308
|
+
console.info(`\u{1F504} Replaced ${unit.kind} "${unit.id}": ${unit.file} \u2192 ${convertedFileName} (backup created)`);
|
|
56074
56309
|
continue;
|
|
56075
56310
|
} catch (backupError) {
|
|
56076
56311
|
conflicts.push({
|
|
@@ -56094,7 +56329,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56094
56329
|
id: unit.id
|
|
56095
56330
|
}
|
|
56096
56331
|
});
|
|
56097
|
-
console.info(
|
|
56332
|
+
console.info(`\u{1F4DD} Renamed ${unit.kind} "${unit.id}": ${unit.file} \u2192 ${(0, path.basename)(uniqueTargetFile)}`);
|
|
56098
56333
|
continue;
|
|
56099
56334
|
} catch (renameError) {
|
|
56100
56335
|
conflicts.push({
|
|
@@ -56132,7 +56367,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56132
56367
|
id: unit.id
|
|
56133
56368
|
}
|
|
56134
56369
|
});
|
|
56135
|
-
console.info(
|
|
56370
|
+
console.info(`\u2713 Copied ${unit.kind} "${unit.id}": ${unit.file} \u2192 ${convertedFileName}`);
|
|
56136
56371
|
} catch (copyError) {
|
|
56137
56372
|
conflicts.push({
|
|
56138
56373
|
unit: {
|
|
@@ -56159,7 +56394,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56159
56394
|
id: "tsconfig.json"
|
|
56160
56395
|
}
|
|
56161
56396
|
});
|
|
56162
|
-
console.info("
|
|
56397
|
+
console.info("\u2713 Copied tsconfig.json from template to target");
|
|
56163
56398
|
} else {
|
|
56164
56399
|
await (0, fs_promises.writeFile)(targetTsconfig, JSON.stringify({
|
|
56165
56400
|
compilerOptions: {
|
|
@@ -56195,7 +56430,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56195
56430
|
id: "tsconfig.json"
|
|
56196
56431
|
}
|
|
56197
56432
|
});
|
|
56198
|
-
console.info("
|
|
56433
|
+
console.info("\u2713 Generated minimal tsconfig.json in target");
|
|
56199
56434
|
}
|
|
56200
56435
|
}
|
|
56201
56436
|
} catch (e) {
|
|
@@ -56224,7 +56459,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56224
56459
|
id: "mastra-index"
|
|
56225
56460
|
}
|
|
56226
56461
|
});
|
|
56227
|
-
console.info("
|
|
56462
|
+
console.info("\u2713 Copied Mastra index file from template");
|
|
56228
56463
|
}
|
|
56229
56464
|
}
|
|
56230
56465
|
} catch (e) {
|
|
@@ -56253,7 +56488,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56253
56488
|
id: "gitignore"
|
|
56254
56489
|
}
|
|
56255
56490
|
});
|
|
56256
|
-
console.info("
|
|
56491
|
+
console.info("\u2713 Copied .gitignore from template to target");
|
|
56257
56492
|
} else {
|
|
56258
56493
|
const targetContent = await (0, fs_promises.readFile)(targetGitignore, "utf-8");
|
|
56259
56494
|
const templateContent = await (0, fs_promises.readFile)(templateGitignore, "utf-8");
|
|
@@ -56269,8 +56504,8 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56269
56504
|
id: "gitignore-merge"
|
|
56270
56505
|
}
|
|
56271
56506
|
});
|
|
56272
|
-
console.info(
|
|
56273
|
-
} else console.info("
|
|
56507
|
+
console.info(`\u2713 Merged template .gitignore entries into existing .gitignore (${addedLines} new entries)`);
|
|
56508
|
+
} else console.info("\u2139 No new .gitignore entries to add from template");
|
|
56274
56509
|
}
|
|
56275
56510
|
}
|
|
56276
56511
|
} catch (e) {
|
|
@@ -56299,7 +56534,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56299
56534
|
id: "env"
|
|
56300
56535
|
}
|
|
56301
56536
|
});
|
|
56302
|
-
console.info(
|
|
56537
|
+
console.info(`\u2713 Created .env file with ${Object.keys(variables).length} template variables`);
|
|
56303
56538
|
} else {
|
|
56304
56539
|
const targetContent = await (0, fs_promises.readFile)(targetEnv, "utf-8");
|
|
56305
56540
|
const mergedContent = mergeEnvFiles(targetContent, variables, slug);
|
|
@@ -56314,8 +56549,8 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56314
56549
|
id: "env-merge"
|
|
56315
56550
|
}
|
|
56316
56551
|
});
|
|
56317
|
-
console.info(
|
|
56318
|
-
} else console.info("
|
|
56552
|
+
console.info(`\u2713 Merged new environment variables into existing .env file (${addedLines} new entries)`);
|
|
56553
|
+
} else console.info("\u2139 No new environment variables to add (all already exist in .env)");
|
|
56319
56554
|
}
|
|
56320
56555
|
}
|
|
56321
56556
|
} catch (e) {
|
|
@@ -56332,7 +56567,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56332
56567
|
if (copiedFiles.length > 0) try {
|
|
56333
56568
|
const fileList = copiedFiles.map((f) => f.destination);
|
|
56334
56569
|
await gitAddAndCommit(targetPath, `feat(template): copy ${copiedFiles.length} files from ${slug}@${commitSha.substring(0, 7)}`, fileList, { skipIfNoStaged: true });
|
|
56335
|
-
console.info(
|
|
56570
|
+
console.info(`\u2713 Committed ${copiedFiles.length} copied files`);
|
|
56336
56571
|
} catch (commitError) {
|
|
56337
56572
|
console.warn("Failed to commit copied files:", commitError);
|
|
56338
56573
|
}
|
|
@@ -56576,7 +56811,7 @@ Start by listing your tasks and work through them systematically!
|
|
|
56576
56811
|
content: toolResult.content || "",
|
|
56577
56812
|
notes: toolResult.notes
|
|
56578
56813
|
});
|
|
56579
|
-
console.info(
|
|
56814
|
+
console.info(`\u{1F4CB} Task completed: ${toolResult.taskId} - ${toolResult.content}`);
|
|
56580
56815
|
}
|
|
56581
56816
|
} catch (parseError) {
|
|
56582
56817
|
console.warn("Failed to parse task management result:", parseError);
|
|
@@ -56628,7 +56863,7 @@ const validationAndFixStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56628
56863
|
const { commitSha, slug, orderedUnits, templateDir, copiedFiles, conflictsResolved, maxIterations = 5 } = inputData;
|
|
56629
56864
|
const targetPath = resolveTargetPath(inputData, requestContext);
|
|
56630
56865
|
if (!(copiedFiles.length > 0 || conflictsResolved && conflictsResolved.length > 0)) {
|
|
56631
|
-
console.info("
|
|
56866
|
+
console.info("\u23ED\uFE0F Skipping validation - no files copied or conflicts resolved");
|
|
56632
56867
|
return {
|
|
56633
56868
|
success: true,
|
|
56634
56869
|
applied: false,
|
|
@@ -56640,7 +56875,7 @@ const validationAndFixStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56640
56875
|
}
|
|
56641
56876
|
};
|
|
56642
56877
|
}
|
|
56643
|
-
console.info(
|
|
56878
|
+
console.info(`\u{1F4CB} Changes detected: ${copiedFiles.length} files copied, ${conflictsResolved?.length || 0} conflicts resolved`);
|
|
56644
56879
|
let currentIteration = 1;
|
|
56645
56880
|
try {
|
|
56646
56881
|
const model = await resolveModel({
|
|
@@ -56732,7 +56967,7 @@ CRITICAL TOOL SELECTION GUIDE:
|
|
|
56732
56967
|
- **writeFile**: ONLY for creating new files that don't exist
|
|
56733
56968
|
Example: creating missing index.ts barrel files
|
|
56734
56969
|
|
|
56735
|
-
CRITICAL WRITEFIL
|
|
56970
|
+
CRITICAL WRITEFIL\u0415 SAFETY RULES:
|
|
56736
56971
|
- ONLY use writeFile for creating NEW files that don't exist
|
|
56737
56972
|
- ALWAYS check with readFile first to verify file doesn't exist
|
|
56738
56973
|
- NEVER use writeFile to overwrite existing files - use multiEdit or replaceLines instead
|
|
@@ -56817,10 +57052,10 @@ Previous iterations may have fixed some issues, so start by re-running validateC
|
|
|
56817
57052
|
if (iterationErrors > 0 && lastValidationResult?.errors) validationResults.lastValidationErrors = lastValidationResult.errors;
|
|
56818
57053
|
console.info(`Iteration ${currentIteration} complete: ${iterationErrors} errors remaining`);
|
|
56819
57054
|
if (iterationErrors === 0) {
|
|
56820
|
-
console.info(
|
|
57055
|
+
console.info(`\u2705 All validation issues resolved in ${currentIteration} iterations!`);
|
|
56821
57056
|
break;
|
|
56822
57057
|
} else if (currentIteration >= maxIterations) {
|
|
56823
|
-
console.info(
|
|
57058
|
+
console.info(`\u26A0\uFE0F Max iterations (${maxIterations}) reached. ${iterationErrors} errors still remaining.`);
|
|
56824
57059
|
break;
|
|
56825
57060
|
}
|
|
56826
57061
|
currentIteration++;
|
|
@@ -56860,7 +57095,7 @@ Previous iterations may have fixed some issues, so start by re-running validateC
|
|
|
56860
57095
|
recursive: true,
|
|
56861
57096
|
force: true
|
|
56862
57097
|
});
|
|
56863
|
-
console.info(
|
|
57098
|
+
console.info(`\u2713 Cleaned up template directory: ${templateDir}`);
|
|
56864
57099
|
} catch (cleanupError) {
|
|
56865
57100
|
console.warn("Failed to cleanup template directory:", cleanupError);
|
|
56866
57101
|
}
|
|
@@ -59954,11 +60189,11 @@ function createPlanningAndApprovalWorkflow() {
|
|
|
59954
60189
|
}
|
|
59955
60190
|
createPlanningAndApprovalWorkflow();
|
|
59956
60191
|
const workflowResearch = `
|
|
59957
|
-
##
|
|
60192
|
+
## \u{1F50D} **COMPREHENSIVE MASTRA WORKFLOW RESEARCH SUMMARY**
|
|
59958
60193
|
|
|
59959
60194
|
Based on extensive research of Mastra documentation and examples, here's essential information for building effective Mastra workflows:
|
|
59960
60195
|
|
|
59961
|
-
###
|
|
60196
|
+
### **\u{1F4CB} WORKFLOW FUNDAMENTALS**
|
|
59962
60197
|
|
|
59963
60198
|
**Core Components:**
|
|
59964
60199
|
- **\`createWorkflow()\`**: Main factory function that creates workflow instances
|
|
@@ -59982,7 +60217,7 @@ const workflow = createWorkflow({
|
|
|
59982
60217
|
.commit(); // CRITICAL: Makes workflow executable
|
|
59983
60218
|
\`\`\`
|
|
59984
60219
|
|
|
59985
|
-
###
|
|
60220
|
+
### **\u{1F527} STEP CREATION PATTERNS**
|
|
59986
60221
|
|
|
59987
60222
|
**Standard Step Definition:**
|
|
59988
60223
|
\`\`\`typescript
|
|
@@ -60006,7 +60241,7 @@ const myStep = createStep({
|
|
|
60006
60241
|
- \`requestContext\`: Runtime dependency injection context
|
|
60007
60242
|
- \`runCount\`: Number of times this step has run (useful for retries)
|
|
60008
60243
|
|
|
60009
|
-
###
|
|
60244
|
+
### **\u{1F504} CONTROL FLOW METHODS**
|
|
60010
60245
|
|
|
60011
60246
|
**Sequential Execution:**
|
|
60012
60247
|
- \`.then(step)\`: Execute steps one after another
|
|
@@ -60028,7 +60263,7 @@ const myStep = createStep({
|
|
|
60028
60263
|
**Data Transformation:**
|
|
60029
60264
|
- \`.map(({ inputData, getStepResult, getInitData }) => transformedData)\`: Transform data between steps
|
|
60030
60265
|
|
|
60031
|
-
###
|
|
60266
|
+
### **\u23F8\uFE0F SUSPEND & RESUME CAPABILITIES**
|
|
60032
60267
|
|
|
60033
60268
|
**For Human-in-the-Loop Workflows:**
|
|
60034
60269
|
\`\`\`typescript
|
|
@@ -60059,7 +60294,7 @@ if (result.status === "suspended") {
|
|
|
60059
60294
|
}
|
|
60060
60295
|
\`\`\`
|
|
60061
60296
|
|
|
60062
|
-
###
|
|
60297
|
+
### **\u{1F6E0}\uFE0F INTEGRATING AGENTS & TOOLS**
|
|
60063
60298
|
|
|
60064
60299
|
**Using Agents in Steps:**
|
|
60065
60300
|
\`\`\`typescript
|
|
@@ -60092,24 +60327,24 @@ const step = createStep({
|
|
|
60092
60327
|
});
|
|
60093
60328
|
\`\`\`
|
|
60094
60329
|
|
|
60095
|
-
###
|
|
60330
|
+
### **\u{1F5C2}\uFE0F PROJECT ORGANIZATION PATTERNS**
|
|
60096
60331
|
|
|
60097
60332
|
**MANDATORY Workflow Organization:**
|
|
60098
60333
|
Each workflow MUST be organized in its own dedicated folder with separated concerns:
|
|
60099
60334
|
|
|
60100
60335
|
\`\`\`
|
|
60101
60336
|
src/mastra/workflows/
|
|
60102
|
-
|
|
60103
|
-
|
|
60104
|
-
|
|
60105
|
-
|
|
60106
|
-
|
|
60107
|
-
|
|
60108
|
-
|
|
60109
|
-
|
|
60110
|
-
|
|
60111
|
-
|
|
60112
|
-
|
|
60337
|
+
\u251C\u2500\u2500 my-workflow-name/ # Kebab-case folder name
|
|
60338
|
+
\u2502 \u251C\u2500\u2500 types.ts # All Zod schemas and TypeScript types
|
|
60339
|
+
\u2502 \u251C\u2500\u2500 steps.ts # All individual step definitions
|
|
60340
|
+
\u2502 \u251C\u2500\u2500 workflow.ts # Main workflow composition and export
|
|
60341
|
+
\u2502 \u2514\u2500\u2500 utils.ts # Helper functions (if needed)
|
|
60342
|
+
\u251C\u2500\u2500 another-workflow/
|
|
60343
|
+
\u2502 \u251C\u2500\u2500 types.ts
|
|
60344
|
+
\u2502 \u251C\u2500\u2500 steps.ts
|
|
60345
|
+
\u2502 \u251C\u2500\u2500 workflow.ts
|
|
60346
|
+
\u2502 \u2514\u2500\u2500 utils.ts
|
|
60347
|
+
\u2514\u2500\u2500 index.ts # Export all workflows
|
|
60113
60348
|
\`\`\`
|
|
60114
60349
|
|
|
60115
60350
|
**CRITICAL File Organization Rules:**
|
|
@@ -60133,7 +60368,7 @@ export const mastra = new Mastra({
|
|
|
60133
60368
|
});
|
|
60134
60369
|
\`\`\`
|
|
60135
60370
|
|
|
60136
|
-
###
|
|
60371
|
+
### **\u{1F4E6} ESSENTIAL DEPENDENCIES**
|
|
60137
60372
|
|
|
60138
60373
|
**Required Packages:**
|
|
60139
60374
|
\`\`\`json
|
|
@@ -60150,7 +60385,7 @@ export const mastra = new Mastra({
|
|
|
60150
60385
|
- \`@ai-sdk/openai\`: For AI model integration
|
|
60151
60386
|
- \`ai\`: For AI SDK functionality
|
|
60152
60387
|
|
|
60153
|
-
###
|
|
60388
|
+
### **\u2705 WORKFLOW BEST PRACTICES**
|
|
60154
60389
|
|
|
60155
60390
|
**Schema Design:**
|
|
60156
60391
|
- Use descriptive property names in schemas
|
|
@@ -60172,7 +60407,7 @@ export const mastra = new Mastra({
|
|
|
60172
60407
|
- Access previous step results with \`getStepResult(stepInstance)\`
|
|
60173
60408
|
- Use \`getInitData()\` to access original workflow input
|
|
60174
60409
|
|
|
60175
|
-
###
|
|
60410
|
+
### **\u{1F680} EXECUTION PATTERNS**
|
|
60176
60411
|
|
|
60177
60412
|
**Running Workflows:**
|
|
60178
60413
|
\`\`\`typescript
|
|
@@ -60195,7 +60430,7 @@ run.watch((event) => console.log(event));
|
|
|
60195
60430
|
- \`"suspended"\`: Paused awaiting input
|
|
60196
60431
|
- \`"failed"\`: Encountered error
|
|
60197
60432
|
|
|
60198
|
-
###
|
|
60433
|
+
### **\u{1F517} ADVANCED FEATURES**
|
|
60199
60434
|
|
|
60200
60435
|
**Nested Workflows:**
|
|
60201
60436
|
- Use workflows as steps: \`.then(otherWorkflow)\`
|
|
@@ -60258,11 +60493,11 @@ CRITICAL WORKFLOW EXECUTION REQUIREMENTS:
|
|
|
60258
60493
|
MANDATORY WORKFLOW FOLDER STRUCTURE:
|
|
60259
60494
|
When ${context.action === "create" ? "creating a new workflow" : "editing a workflow"}, you MUST organize files as follows:
|
|
60260
60495
|
|
|
60261
|
-
|
|
60262
|
-
|
|
60263
|
-
|
|
60264
|
-
|
|
60265
|
-
|
|
60496
|
+
\u{1F4C1} src/mastra/workflows/${context.workflowName?.toLowerCase().replace(/[^a-z0-9]/g, "-") || "new-workflow"}/
|
|
60497
|
+
\u251C\u2500\u2500 \u{1F4C4} types.ts # All Zod schemas and TypeScript types
|
|
60498
|
+
\u251C\u2500\u2500 \u{1F4C4} steps.ts # All individual step definitions
|
|
60499
|
+
\u251C\u2500\u2500 \u{1F4C4} workflow.ts # Main workflow composition and export
|
|
60500
|
+
\u2514\u2500\u2500 \u{1F4C4} utils.ts # Helper functions (if needed)
|
|
60266
60501
|
|
|
60267
60502
|
CRITICAL FILE ORGANIZATION RULES:
|
|
60268
60503
|
- **ALWAYS create a dedicated folder** for the workflow in src/mastra/workflows/
|
|
@@ -60334,7 +60569,7 @@ ${context.resumeData ? `USER PROVIDED ANSWERS: ${JSON.stringify(context.resumeDa
|
|
|
60334
60569
|
},
|
|
60335
60570
|
validation: { instructions: `CRITICAL VALIDATION INSTRUCTIONS:
|
|
60336
60571
|
- When using the validateCode tool, ALWAYS pass the specific files you created or modified using the 'files' parameter
|
|
60337
|
-
- The tool uses a hybrid validation approach: fast syntax checking
|
|
60572
|
+
- The tool uses a hybrid validation approach: fast syntax checking \u2192 semantic type checking \u2192 ESLint
|
|
60338
60573
|
- This is much faster than full project compilation and only shows errors from your specific files
|
|
60339
60574
|
- Example: validateCode({ validationType: ['types', 'lint'], files: ['src/workflows/my-workflow.ts', 'src/agents/my-agent.ts'] })
|
|
60340
60575
|
- ALWAYS validate after creating or modifying files to ensure they compile correctly` }
|